我应该使用哪种方法?

时间:2013-01-13 22:24:41

标签: python class methods

>>> class StrictList(list):
...     def __init__(self,content=None):
...         if not content:
...             self.content = []
...             self.type = None
...         else:
...             content = list(content)
...             cc = content[0].__class__
...             if l_any(lambda x: x.__class__ != cc, content):
...                 raise Exception("List items must be of the same type")
...             else:
...                 self.content = content
...                 self.type = cc
... 
>>> x = StrictList([1,2,3,4,5])
>>> x
[]
>>> x.content
[1, 2, 3, 4, 5]

我希望能够在致电x而不是x.content

时退回内容

1 个答案:

答案 0 :(得分:2)

您正尝试继承list但从不调用列表__init__方法。加上这个:

super(StrictList, self).__init__(content)

将项目添加到自己。无需分配到self.content

>>> class StrictList(list):
...     def __init__(self,content=None):
...         super(StrictList, self).__init__(content)
... 
>>> s = StrictList([1, 2, 3])
>>> len(s)
3
>>> s[0]
1