【问题标题】:AttributeError when using object.__setattr__使用 object.__setattr__ 时出现 AttributeError
【发布时间】:2012-10-11 11:57:19
【问题描述】:

最后三行有什么问题?

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

【问题讨论】:

    标签: python object setattr


    【解决方案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)
    

    【讨论】:

    • l = list(); l.attr = 7; AttributeError...我猜你是对的!
    【解决方案2】:

    您不能将新属性添加到 object(),只能添加到子类。

    试试collections.NamedTuples。

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

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      相关资源
      最近更新 更多