【发布时间】:2013-04-22 07:43:06
【问题描述】:
考虑一下这段 Python 代码:
>>> l = [1,2,3]
>>> l.foo = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'foo'
>>> setattr(l, 'foo', 'bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'foo'
我明白为什么这不起作用 -- list 没有 __dict__ 因此它不支持属性。
我想知道是否有推荐的替代列表集合类支持自定义属性,或者是否有一个好的 Pythonic 'hack' 可用于将其添加到标准 list 类中。
或者在这种情况下,您自己推出更简单?
【问题讨论】:
标签: python list properties python-2.7