簡體   English   中英

使用object .__ setattr__時發生AttributeError

[英]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內置類型 ,因此您不能覆蓋其實例的屬性和方法。

也許您只想要一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)

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

嘗試collections.NamedTuple

此外,代替object.__setattr__(foo1,'attribute','Hi')setattr(foo1, 'attribute', 'Hi')會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM