『Python』__getattr__()特殊方法

 self的认识 & __getattr__()特殊方法

将字典调用方式改为通过属性查询的一个小class,

class Dict(dict):
 
    def __init__(self, **kw):
        super(Dict, self).__init__(**kw)
 
    def __getattr__(self, key):
        try:
            print(self)
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
 
 
if __name__ == '__main__':
    d = Dict(a=1, b=2)
    print(d.a)
{'a': 1, 'b': 2}
1

1,__getattr__()方法可以接受属性值,并动态的赋予实例属性

2,果然,self在类内部代表的是实例,self['b']就是因为__init__继承了父类的初始化,所以self才有['b']查询方法。

原文地址:https://www.cnblogs.com/hellcat/p/7978904.html