2012-10-11 22 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')会更好。

相关问题