0
我是一名刚接触python的学生。我想要定义一个数组类,它使用字典作为其唯一的成员变量。我假定Python实现了字典作为唯一的结构化类型(即没有数组,列表,元组等)。仅使用字典创建数组类
我在编写这样的程序时遇到了困难。
这是我的代码:
class array(object):
def __init__(self):
self.dic={}
def __init__(self,diction):
self.dic = {}
for x in diction:
self.dic.append(x)
def __setitem__(self,key,value):
self.dic[key]=value
def __getitem__(self,key):
if key not in self.dic.keys():
raise KeyError
return self.dic[key]
我想要的程序这样的工作方式:
a = array('a','b','c') #------output------
print(a) # ['a', 'b', 'c']
print(a[1]) # b
a[1] = 'bee'
print(a) # ['a', 'bee', 'c']
a[3] = 'day'
print(a) # ['a', 'bee', 'c', 'day']
print(a[6]) # IndexError exception
任何建议,意见。 :)
为什么你有2 __init__函数? –
Python不支持多重构造函数的重载,所以只会使用一个'__init__'(第二个)。使用默认参数 –
我还建议您不要调用您的类数组 - 您将与相同名称的python数据结构发生冲突。改称MyArray或其他。 –