python __getattr__()、__call__

__getattr__()方法

正常情况下,当我们调用类的方法或者属性时,如果搜索不到对应的方法或者属性,就会报错。

>>> class Student(object):
...     def __init__(self):
...             self.name = 'Micheal'
... 
>>> s = Student()
>>> print s.name
Micheal
>>> print s.score
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

要避免这个错误,除了可以加上一个score属性外,python还有另外一个机制,那就是重写一个__getattr__()方法,动态返回一个属性。

class Student(object):

    def __init__(self):
        self.name = 'Michael'

    def __getattr__(self, attr):
        if attr=='score':
            return 99

当调用不存在的属性的时候,比如score,python解释器就会调用__getattr__(self, 'score') 来尝试获得属性。
注意:这里自动把不存在的属性转换为了字符串的形式,然后传到函数__getattr__(self,attr)__ 中,并赋值给attr,所以这是的attr是一个字符串。

>>> s = Student()
>>> s.name
'Michael'
>>> s.score
99

返回函数也是完全可以的:

class Student(object):
    def __getattr__(self, attr):
        if attr=='age':
            return lambda: 25

只是调用方式要变为,因为返回的是一个函数对象(类似函数指针)

>>> s.age()
25

注意,只有在没有找到属性的情况下,才调用__getattr__ ,已有的属性,比如name,不会在__getattr__ 中查找。

此外,注意到任意调用如s.abc都会返回None,这是因为我们定义的__getattr__ 默认返回就是None。要让class只响应特定的几个属性,我们就要按照约定,抛出AttributeError的错误:

class Student(object):

    def __getattr__(self, attr):
        if attr=='age':
            return lambda: 25
        raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)

这实际上可以把一个类的所有属性和方法调用全部动态化处理了,不需要任何特殊手段。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值