最后三行出了什么问题?
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)吗?
答案 0 :(得分:1)
object
是built-in type,因此您无法覆盖其实例的属性和方法。
也许您只想要一个dictionary
或collections.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)
答案 1 :(得分:0)
您无法向object()
添加新属性,只能添加子类。
尝试collections.NamedTuple
s。
此外,代替object.__setattr__(foo1,'attribute','Hi')
,setattr(foo1, 'attribute', 'Hi')
会更好。