在类中将__setattr__方法与getattr一起使用

时间:2019-02-26 07:16:11

标签: python python-3.x class getattr setattr

我有一个如下的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也将开始工作。这是什么问题?

1 个答案:

答案 0 :(得分:2)

您应该调用__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)