python __getattr__

2018-09-26  本文已影响0人  tafanfly

__getattr__

这是python里的一个内建函数,当调用的属性或者方法不存在时,该方法会被调用

 class Student(object):
     def __getattr__(self, attr):
         if attr in ('name', 'age', 'score'):
             print attr
         else:
             raise AttributeError('Unkonw attribute : %s' % attr)


In [8]: student = Student()

In [9]: student.name
name

In [10]: student.age
age

In [11]: student.call
AttributeError: Unkonw attribute : call
 class Student(object):
     def __getattr__(self, attr):
         def _func(*arg, **kwargs):
             print arg, kwarg

         if not attr.startswith('_'):
             _func.func_name = attr
             return _func
         raise AttributeError('Unkonw attribute : %s' % attr)

In [22]: student = Student()

In [23]: student.name
Out[23]: <function __main__.name>

In [24]: student.name('a', 'b', c=1, d=2)
('a', 'b') {'c': 1, 'd': 2}
In [25]: student._age('a', 'b', c=1, d=2)

AttributeError: Unkonw attribute : _age

例一: 访问属性一样访问dict中的键值对

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

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

In [27]: obj = Dict(student={'age': 18}, name='ZhangSan')

In [28]: obj
Out[28]: {'name': 'ZhangSan', 'student': {'age': 18}}

In [29]: obj.name
Out[29]: 'ZhangSan'

In [30]: obj.student
Out[30]: {'age': 18}

In [31]: obj.student.age
Out[31]: 18
上一篇下一篇

猜你喜欢

热点阅读