是否有像__getattr__这样的函数被类变量调用? [英] Is there a function like __getattr__ that gets called for class variables?

查看:107
本文介绍了是否有像__getattr__这样的函数被类变量调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重新定义对象的get函数,以便可以在请求任何属性时进行拦截.使用 getattr 函数,它不会在请求现有变量(例如本例中的attr1)时捕获.有没有办法解决这个问题,所以我可以在请求attr1时运行一个函数?

I want to redefine an object's get function so that I can intercept when any attribute is requested. Using the getattr function, it doesn't catch when existing variables (eg. attr1 in this case) are requested. Is there a way around this, so I can run a function when attr1 is requested?

class Test(object):
    attr1 = 1
    def __init__(self):
        self.attr2 = 1
    def __getattr__(self, attr):
        print 'GETATTR', attr
a = Test()
a.attr1
a.attr2
a.attr3

输出:

GETATTR attr3

我也想在输出中看到GETATTR attr1和GETATTR attr2.

I'd like to see GETATTR attr1 and GETATTR attr2 in the output too.

推荐答案

这与类或实例变量无关.这取决于属性是否存在;您的attr1存在,但其他人不存在. (您对attr2所做的操作不会创建属性;您只是创建一个局部变量并将其丢弃.如果您执行self.attr2 = 1,您会发现__getattr__也不会被attr2调用. )

It's not a matter of class or instance variables. It's a matter of whether the attribute exists or not; your attr1 exists but the others do not. (What you do with attr2 does not create an attribute; you're just creating a local variable and throwing it away. If you do self.attr2 = 1, you will see that __getattr__ is not called for attr2 either.)

已记录__getattr__称为属性查找未在通常的地方找到该属性(即它不是实例属性,也不是在自身的类树中找到)".同样在同一地方记录的内容,还有另一个魔术方法__getattribute__,即使该属性确实存在,该方法也总是被调用.

As documented, __getattr__ is called "when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self)". As also documented in the same place, there is another magic method __getattribute__ which is always called, even when the attribute does exist.

这篇关于是否有像__getattr__这样的函数被类变量调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆