python getattr_python __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]:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值