繁体   English   中英

为什么这个 __getattr__ function 不起作用?

[英]Why does this __getattr__ function not work?

我有这个小 class 我写来尝试使用自定义__getattr__方法,每次运行它时,我都会收到一个属性错误:

class test:
    def __init__(self):
        self.attrs ={'attr':'hello'}
    def __getattr__(self, name):
        if name in self.attrs:
            return self.attrs[name]
        else:
            raise AttributeError

t = test()
print test.attr

output 则为:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print test.attr
AttributeError: class test has no attribute 'attr'

是什么赋予了? 我认为在引发属性错误之前调用了getattr

因为 class test没有attr作为属性,所以实例t有:

class test:
    def __init__(self):
        self.attrs ={'attr':'hello'}
    def __getattr__(self, name):
        if name in self.attrs:
            return self.attrs[name]
        else:
            raise AttributeError

t = test()
print t.attr

您必须查询实例( t ) 上的属性,而不是class ( test ) 上的属性:

>>> t = test()
>>> print t.attr
hello

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM