Python 使用对象时属性错误。\uuu setattr__

Python 使用对象时属性错误。\uuu setattr__,python,object,setattr,Python,Object,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' o

最后三行怎么了

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)吗

对象
是,因此不能覆盖其实例的属性和方法

也许你只是想要一个或:


不能将新属性添加到
对象()
,只能添加到子类

尝试
collections.NamedTuple
s

此外,与其使用对象,不如使用setattr(foo1,'attribute','Hi'),
setattr(foo1,'attribute','Hi')
;l、 attr=7;属性错误。。。我想你是对的!
>>> 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)