在 class 中使用带有 getattr 的 __setattr__ 方法
Using __setattr__ method with getattr in a class
我有一个Pythonclass如下:
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
效果很好。
现在我又介绍了一个class属性,其值通过字典查找初始化如下:
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'
我在做什么 wrong.Also 如果我删除 __setattr__
方法,getattr
就会开始工作。这里有什么问题?
我有一个Pythonclass如下:
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
效果很好。
现在我又介绍了一个class属性,其值通过字典查找初始化如下:
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'
我在做什么 wrong.Also 如果我删除 __setattr__
方法,getattr
就会开始工作。这里有什么问题?