我是一名刚接触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
任何建议,意见。 :)
答案 0 :(得分:1)
您的班级定义存在很多问题:
array
已经是一个数据结构:最好使用正确的Python类命名约定(MyClass
)进行重命名。*
)来提取所有(如果有)参数。print
的调用将显示通用类名,因为您未指定__str__
魔法。由于dict
是无序的,我在这里做了一些有趣的事情,使它显示为排序,但我确信有更好的方法。KeyError
中提出__getitem__
,因为无论如何都会提出。{/ li>
请注意,我只实现了使测试用例工作所必需的方法。
class MyArray(object):
def __init__(self, *diction):
self.dic = {}
for i, x in enumerate(diction):
self.dic[i] = x
def __setitem__(self, key, value):
self.dic[key] = value
def __getitem__(self, key):
return self.dic[key]
def __str__(self):
return str([self.dic[i] for i in sorted(self.dic.keys())])