Descriptor HowTo Guide
Abstract
检查自定义描述符和内置的描述符包括函数、属性、静态方法、类方法。帮助我们深入了解python工作方式。
- __get__()
- __set__()
- __delete__()
data descriptor
获取对象的属性时自动调用描述符方法。
- 对象:object.getattribute():transforms b.x into type(b).dict['x'].get(b, type(b))
- 类:type.getattribute():transforms B.x into B.dict['x'].get(None, B).
The important points to remember are:
- descriptors are invoked by the __getattribute__() method
- overriding __getattribute__() prevents automatic descriptor calls
- __getattribute__() is only available with new style classes and objects
- object.__getattribute__() and type.__getattribute__() make different calls to __get__().`
- data descriptors always override instance dictionaries.
- non-data descriptors may be overridden by instance dictionaries.
类在定义函数时,通过字典保存函数的地址,__get__()
方法获取函数。
unbound method&bound method
Likewise, the effects of calling a method object depend on the im_self field. If set (meaning bound), the original function (stored in the im_func field) is called as expected with the first argument set to the instance. If unbound, all of the arguments are passed unchanged to the original function. The actual C implementation of instancemethod_call() is only slightly more complex in that it includes some type checking.
Static Methods and Class Methods
函数有__get__()
方法将自己转换成方法。
The non-data descriptor transforms an obj.f(*args) call into f(obj, *args). Calling klass.f(*args) becomes f(*args).