python - 使用 setattr() 时出现 AttributeError
问题描述
下面提出一个AttributeError: 'objval' object has no attribute 'testitem'
class objval(object):
def __init__(self):
self.testitem = 1
def __setattr__(self, key, value):
print('setattr: ' + str(key) + '=' + str(value))
testobj = objval()
print(testobj.testitem)
尽管现在删除def __setattr__(self, key, value):
打印时testobj.testitem
正确输出了该值。
解决方案
您正在覆盖类对象的setattr方法。像这样它可以工作并显示您的属性。我刚刚添加了 super 方法,让您的对象在更改后执行原始setattr方法:
class objval(object):
def __init__(self):
self.testitem = 1
def __setattr__(self, key, value):
print('setattr: ' + str(key) + '=' + str(value))
super(objval, self).__setattr__(key, value)
testobj = objval()
print(testobj.testitem)
推荐阅读
- python - 列表中最大 n 个元素的项目和索引
- javascript - 我有一个代码无法识别的声明变量。为什么是这样?
- search - Microsoft.Azure.CognitiveServices.Search.EntitySearch.EntitySearchClient.Entities.Search(位置:
:? :? - mdm - 如何将内部应用“提升”到更高级别的组织?
- netty - 未为 netty 中的每个请求创建新的处理程序
- mysql - 奇怪的查询,不确定是否需要嵌套?这里有什么问题?
- android - 设置 android hello world 测试用例时出错
- python - 如何在 keras 中实现 ssim 的损失函数?
- java - 如何修复“11”不断重复
- javascript - 从js调用函数但它不起作用