简体   繁体   English

使用object .__ setattr__时发生AttributeError

[英]AttributeError when using object.__setattr__

What's wrong with the last three lines? 最后三行怎么了?

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'

I need an object having a single attribute (like foo) should I define a class (like FooClass) just for it? 我需要一个具有单个属性的对象(例如foo),是否应该为此定义一个类(例如FooClass)?

object is built-in type , so you can't override attributes and methods of its instances. object内置类型 ,因此您不能覆盖其实例的属性和方法。

Maybe you just want a dictionary or collections.NamedTuples : 也许您只想要一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)

You cannot add new attributes to an object() , only to subclasses. 您不能将新属性添加到object() ,而只能添加到子类。

Try collections.NamedTuple s. 尝试collections.NamedTuple

Besides, instead of object.__setattr__(foo1,'attribute','Hi') , setattr(foo1, 'attribute', 'Hi') would be better. 此外,代替object.__setattr__(foo1,'attribute','Hi')setattr(foo1, 'attribute', 'Hi')会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用object .__ setattr __(self,…,…)`而不是`setattr(self,…,…)`? - `object.__setattr__(self, …, …)` instead of `setattr(self, …, …)`? setattr(object,name,value)vs object .__ setattr __(name,value) - setattr(object, name, value) vs object.__setattr__(name,value) python 冻结数据类与 object.__setattr__ 不可变 - python frozen dataclass immutable with object.__setattr__ 从对象类型.__ setattr__有多么不同.__ setattr__? - How different is type.__setattr__ from object.__setattr__? setattr()和object .__ setattr __()之间有什么区别? - What's the difference between setattr() and object.__setattr__()? object .__ setattr __()和直接设置之间有什么区别吗? - Is there any difference between object.__setattr__() and directly set? Python 2.7:object .__ setattr__在后台做什么? - Python 2.7: What does object.__setattr__ do under the hood? 为什么只在新样式类中支持object .__ setattr __(self,name,value)? - Why favor object.__setattr__(self, name, value) only in new style classes? python:setattr AttributeError:object 没有属性 - python: setattr AttributeError: object has no attribute 使用setattr()更新对象实例 - Using setattr() to update an object instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM