首页 > 解决方案 > 为什么设置类对象实例的属性会导致 AttributeError?

问题描述

为什么以下代码会产生错误

>>> object().foo = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo' 

而下一个工作正常?

class A():
    pass

A().foo = 'bar'

A和object之间的确切区别是什么?我相信o().foo = 'bar'会导致setattr('o', 'foo', 'bar'),这反过来会导致o.__setattr__('foo', 'bar'). 人们会期望它们具有相同的__setattr__方法,因为没有发生覆盖。然而输出是不同的。请解释原因。幕后会发生什么?

对于内置函数和用户定义的函数,可以注意到类似的模式。我不能设置我自己的属性,比如说dict,但是写起来完全没问题(lambda:None).foo = 'bar'。这里发生了什么?

标签: python-3.x

解决方案


推荐阅读