我有一个如下的Python类:
class Base:
def __init__(self, response=20):
self.response = response
def func1(self):
self.response = 10
def func2(self):
self.response = 20
def func3(self):
self.response = 30
每次响应值更改时,我都需要捕获它。因此,我定义了一种__setattr__
方法,如下所示:
class Base:
def __init__(self, response=20):
self.response = response
def __setattr__(self, name, value):
if name == 'response':
print('{} is set to {}'.format(name, value))
def func1(self):
self.response = 10
def func2(self):
self.response = 20
def func3(self):
self.response = 30
输出:
=============================================================
In [10]: a = Base()
response is set to 20
In [11]: a.func1()
response is set to 10
In [12]: a.func2()
response is set to 20
效果很好。
现在,我又引入了一个类属性,该类属性的值通过字典查找进行初始化,如下所示:
my_dict = {20:'key1'}
class Base:
def __init__(self, response=20):
self.response = response
self.key = getattr(my_dict,self.response).value
def __setattr__(self, name, value):
if name == 'response':
print('{} is set to {}'.format(name, value))
def func1(self):
self.response = 10
def func2(self):
self.response = 20
def func3(self):
self.response = 30
这会显示错误消息:
----> 6 self.key = getattr(my_dict,self.response)
AttributeError: 'Base' object has no attribute 'response'
我在做什么错。此外,如果删除__setattr__
方法,getattr
也将开始工作。这是什么问题?