下面引发一个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现在会正确地输出值。
发布于 2020-07-09 09:27:16
您正在重写类对象的setattr方法。就像这样,它起作用,并输出您的属性。我刚刚添加了超级方法,让对象在更改后执行原始的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)https://stackoverflow.com/questions/62811601
复制相似问题