python中__get__,__getattr__,__getattribute__的区别,__get____getattr__,object.__g
python中__get__,__getattr__,__getattribute__的区别,__get____getattr__,object.__g
__get__,__getattr__和__getattribute都是访问属性的方法,但不太相同。
object.__getattr__(self, name)
当一般位置找不到attribute的时候,会调用getattr,返回一个值或AttributeError异常。
object.__getattribute__(self, name)
无条件被调用,通过实例访问属性。如果class中定义了__getattr__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常)
object.__get__(self, instance, owner)
只用在descriptor中。可以通过owner class或者instance来访问属性。
class C(object): a = 'abc' def __getattribute__(self, *args, **kwargs): print("__getattribute__() is called") return object.__getattribute__(self, *args, **kwargs) # return "haha" def __getattr__(self, name): print("__getattr__() is called ") return name + " from getattr" def __get__(self, instance, owner): print("__get__() is called", instance, owner) return self def foo(self, x): print(x) class C2(object): d = C() if __name__ == '__main__': c = C() c2 = C2() print(c.a) print(c.zzzzzzzz) c2.d print(c2.d.a)
输出结果是:
__getattribute__() is called
abc
__getattribute__() is called
__getattr__() is called
zzzzzzzz from getattr
__get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'>
__get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'>
__getattribute__() is called
abc
小结:可以看出,每次通过实例访问属性,都会经过__getattribute__函数。而当属性不存在时,仍然需要访问__getattribute__,不过接着要访问__getattr__。这就好像是一个异常处理函数。
每次访问descriptor(即实现了__get__的类),都会先经过__get__函数。
需要注意的是,当使用类访问不存在的变量是,不会经过__getattr__函数。而descriptor不存在此问题,只是把instance标识为none而已。
相关内容
- Python基础1 Hello World!,pythonhello,最最基础的当然是he
- python基础 python内置函数map/reduce/filter,pythonreduce,filte
- python基础 python类的成员和装饰器,python装饰,这里只着
- python操作字典类型的常用方法总结,python字典,语法格式
- Python集合(set)类型的操作总结,pythonset,作为一个无序
- 用python求第1000个质数的值,python1000质数,质数:只能被
- 用python脚本计算某一个文件的行数,python脚本行数,下面
- python基础 - python命名空间与作用域,python命名空间,命名
- python基础之列表拷贝,python列表拷贝,我先定义一个列表
- python全局变量与局部变量,python全局变量变量,函数内的
评论关闭