2013-04-28 109 views
1

设置列表对象上的属性考虑此位的Python代码:在Python 2.7

>>> 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类。

或者这是一个更简单的情况下推出自己的?

回答

4
>>> class Foo(list): pass 
>>> l = Foo([1,2,3]) 
>>> l.foo = 'bar' 
>>> l 
[1, 2, 3] 
+0

呀使用,仅此而已。将它包装在一个班级中。大脑褪色...感谢提醒... – Inactivist 2013-04-28 16:45:00

+0

@Eric什么是'foo'在'l.foo ='bar''上有小帽子 – octoback 2013-04-28 18:51:07

+0

@antitrust:你的意思是小写吗?这只是一个属性的任意名称。与'Foo'的相似性是巧合的 – Eric 2013-04-28 22:26:10

0

这是使用setattr您试图在首位

>>> l = [1,2,3] 
>>> lst = Foo(l) 
>>> setattr(lst, 'foo', 'bar') 
>>> lst.foo 
'bar'