python-3.x - 为什么设置类对象实例的属性会导致 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'
。这里发生了什么?
解决方案
推荐阅读
- seaborn - Seaborn 热图
- html - Div 不会缩放到图像元素调整大小
- python - Lambda 层 TensorFlow 的多个输入
- documentum - 是否可以更改 dm_document 类型的本机文档属性的长度?
- javascript - 如果在 Woocommerce 中未选中复选框,则隐藏元素
- sql - 如何为维度中的每个类别添加一组日期?
- html - HTML 电子邮件 - 按钮在 Outlook 上没有填充
- javascript - React 重用 reactElement,reactElement 状态会被重置
- html - 在多行上换行
- java - SimpleJdbcCall 存储过程调用在第一次调用后失败