我应该用哪种方法?

2024-04-19 18:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> 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时返回内容


Tags: lambdaselfnoneifinitdeftypenot
1条回答
网友
1楼 · 发布于 2024-04-19 18:32:28

您正在尝试子类list,但从未调用list__init__方法。添加以下内容:

super(StrictList, self).__init__(content)

将项目添加到self。无需分配给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

相关问题 更多 >