2012-10-11 23 views
2

最後三行有什麼問題?使用object時的AttributeError .__ setattr__

class FooClass(object): 
    pass 
bar1 = object() 
bar2 = object() 
bar3 = object() 
foo1 = FooClass() 
foo2 = FooClass() 
foo3 = FooClass() 
object.__setattr__(foo1,'attribute','Hi') 
foo2.__setattr__('attribute','Hi') 
foo3.attribute = 'Hi' 
object.__setattr__(bar1,'attribute','Hi') 
bar2.attribute = 'Hi' 
bar3.attribute = 'Hi' 

我需要具有單個屬性(類似foo)的對象我應該定義一個類(如FooClass)只是呢?

回答

1

objectbuilt-in type,所以你不能覆蓋它的實例的屬性和方法。

也許你只是想要一個dictionarycollections.NamedTuples

>>> d = dict(foo=42) 
{'foo': 42} 
>>> d["foo"] 
42 

>>> from collections import namedtuple 
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True) 
>>> p = Point(11, y=22)  # instantiate with positional or keyword arguments 
>>> p[0] + p[1]    # indexable like the plain tuple (11, 22) 33 
>>> x, y = p    # unpack like a regular tuple 
>>> x, y (11, 22) 
>>> p.x + p.y    # fields also accessible by name 33 
>>> p      # readable __repr__ with a name=value style Point(x=11, y=22) 
+0

l = list(); l.attr = 7; AttributeError ...我想你是對的! – jimifiki

0

您不能將新的屬性添加到object(),只有子類。

嘗試collections.NamedTuple s。

此外,而不是object.__setattr__(foo1,'attribute','Hi'),setattr(foo1, 'attribute', 'Hi')會更好。

相關問題