Python语言学习讲解十七:python之__gettattr__、__getattribute__和__setattr__详解
2016-12-01 15:49
591 查看
注:每周一到周五都会进行相关Python基础知识更新,欢迎大家提宝贵的意见
python语言提供了一种挂钩,使得开发者能够很方便的编写出通用代码,他们使用的不是普通实例的属性,@property方法和描述符,而是使用的是python的魔术方法
__gettattr__、__getattribute__和__setattr__,他们属于动态行为。
>>> class TEST(object):
def __init__(self):
self.value = 1
def __getattr__(self, name):
value = 'Value for %s' % name
setattr(self, name, value)
return value
>>> testobj = TEST()
>>> print('---:',testobj.__dict__)
{'__methods__': 'Value for __methods__', '__members__': 'Value for __members__', 'value': 1}
>>> print(testobj.__dict__)
{'__methods__': 'Value for __methods__', '__members__': 'Value for __members__', 'value': 1}
>>> print(testobj.attr)
'Value for attr'
>>> print(testobj.__dict__)
{'__methods__': 'Value for __methods__', '__members__': 'Value for __members__', 'value': 1, 'attr': 'Value for attr'}
总结:
__gettattr__:如果某个类定义了这个方法,并且在该类的对象的字典中又找不到相应的属性时候,那么次方法会被调用。
__getattribute__:不管对象的字典中有没有找到对应的属性,都会调用
__setattr__:无论是直接赋值还是通过内置的setattr函数赋值,都会调用
********还有一点需要住的是__[b]getattribute__和__setattr__方法中访问实例属性的时候,应该直接通过super()来做,避免无线递归。******[/b]
python语言提供了一种挂钩,使得开发者能够很方便的编写出通用代码,他们使用的不是普通实例的属性,@property方法和描述符,而是使用的是python的魔术方法
__gettattr__、__getattribute__和__setattr__,他们属于动态行为。
>>> class TEST(object):
def __init__(self):
self.value = 1
def __getattr__(self, name):
value = 'Value for %s' % name
setattr(self, name, value)
return value
>>> testobj = TEST()
>>> print('---:',testobj.__dict__)
{'__methods__': 'Value for __methods__', '__members__': 'Value for __members__', 'value': 1}
>>> print(testobj.__dict__)
{'__methods__': 'Value for __methods__', '__members__': 'Value for __members__', 'value': 1}
>>> print(testobj.attr)
'Value for attr'
>>> print(testobj.__dict__)
{'__methods__': 'Value for __methods__', '__members__': 'Value for __members__', 'value': 1, 'attr': 'Value for attr'}
总结:
__gettattr__:如果某个类定义了这个方法,并且在该类的对象的字典中又找不到相应的属性时候,那么次方法会被调用。
__getattribute__:不管对象的字典中有没有找到对应的属性,都会调用
__setattr__:无论是直接赋值还是通过内置的setattr函数赋值,都会调用
********还有一点需要住的是__[b]getattribute__和__setattr__方法中访问实例属性的时候,应该直接通过super()来做,避免无线递归。******[/b]
相关文章推荐
- Python语言学习讲解五:列表(List)操作方法详解
- Python语言学习讲解十八: __new__、__init__、__call__之详解
- Python语言学习讲解三:详解Python中的split()函数的使用方法
- Python语言学习讲解八:类型判断type与isinstance的区别
- Python语言学习讲解十二:nonlocal关键字
- Python语言学习讲解四:常见的几个坑
- Python语言学习讲解十六:python之描述符__set__和__get__ 等解释
- Python语言学习讲解十九: 异常信息的详细获取
- Python语言学习讲解六:增强的格式化字符串format函数
- Python语言学习讲解十四:python之用纯属性取代get和set方法
- Python语言学习讲解十:列表推导式
- Python语言学习讲解一:【赋值、浅拷贝与深拷贝】
- Python语言学习讲解七:使用traceback获取详细的异常信息
- Python语言学习讲解十三:python之多进程和多线程
- python __setattr__、__getattr__、__getattribute__全面详解
- Python语言学习讲解十一:生成器表达式改写较大的列表推导
- Python语言学习讲解九:偏函数functools.partial
- Python语言学习讲解二:@staticmethod和@classmethod的作用与区别
- Python语言学习讲解七:使用traceback获取详细的异常信息
- Python学习之基础语言篇——函数参数详解