[英]`object.__setattr__(self, …, …)` instead of `setattr(self, …, …)`?
[英]AttributeError when using 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'
object.__setattr__(bar1,'attribute','Hi')
bar2.attribute = 'Hi'
bar3.attribute = 'Hi'
我需要一個具有單個屬性的對象(例如foo),是否應該為此定義一個類(例如FooClass)?
object
是內置類型 ,因此您不能覆蓋其實例的屬性和方法。
也許您只想要一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)
您不能將新屬性添加到object()
,而只能添加到子類。
嘗試collections.NamedTuple
。
此外,代替object.__setattr__(foo1,'attribute','Hi')
, setattr(foo1, 'attribute', 'Hi')
會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.