在 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 就会开始工作。这里有什么问题?

您应该调用 __setattr__ 的父实现来实际创建属性:

def __setattr__(self, name, value):
    if name == 'response':
        print('{} is set to {}'.format(name, value))
    super.__setattr__(self,name,value)

此外,如果您想要与字典键关联的值,请使用:

self.key = my_dict.get(self.response)

您可以通过查看官方文档找到更多详细信息here(3.7)here(2.7)