首页 > 解决方案 > 使用 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正确输出了该值。

标签: pythonpython-3.x

解决方案


您正在覆盖类对象的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)

推荐阅读