Python的__getattr__方法学习

__getattr__函数的作用: 如果属性查找(attribute lookup)在实例以及对应的类中(通过__dict__)失败, 那么会调用到类的__getattr__函数;

如果没有定义这个函数,那么抛出AttributeError异常。由此可见,__getattr__一定是作用于属性查找的最后一步

举个栗子:

class A(object):
    def __init__(self, a, b):
        self.a1 = a
        self.b1 = b
        print('init')

    def mydefault(self, *args):
        print('default:' + str(args[0]))

    def __getattr__(self, name):
        print("other fn:", name)
        return self.mydefault


a1 = A(10, 20)
a1.fn1(33)
a1.fn2('hello')

运行结果:

init
other fn: fn1
default:33
other fn: fn2
default:hello

第16行调用fn1属性时,查找不到次属性,程序调用__getattr__方法

__getattr__方法可以处理调用属性异常

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Student(object):
    def __getattr__(self, attrname):
        if attrname == "age":
            return 'age:40'
        else:
            raise AttributeError(attrname)

x = Student()
print(x.age)  # 40
print(x.name)

这里定义一个Student类和实例x,并没有属性age,当执行x.age,就调用_getattr_方法动态创建一个属性,执行x.name时,__getattr__方法没有对其处理,抛出异常

age:40
  File "XXXX.py", line 10, in <module>
    print(x.name)
  File "XXXX.py", line 6, in __getattr__
    raise AttributeError(attrname)
AttributeError: name

下面展示一个_getattr_经典应用的例子,可以调用dict的键值对

class ObjectDict(dict):
    def __init__(self, *args, **kwargs):
        super(ObjectDict, self).__init__(*args, **kwargs)

    def __getattr__(self, name):
        value = self[name]
        if isinstance(value, dict):
            value = ObjectDict(value)
        return value


if __name__ == '__main__':
    od = ObjectDict(asf = {'a': 1}, d = True)
    print(od.asf, od.asf.a)  # {'a': 1} 1
    print(od.d)  # True
  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值