【发布时间】:2020-02-27 18:10:37
【问题描述】:
我试图了解描述符在 python 中是如何工作的。我得到了大局,但我在理解 @staticmethod 装饰器时遇到了问题。
我特指的代码来自对应的python doc:https://docs.python.org/3/howto/descriptor.html
class Function(object):
. . .
def __get__(self, obj, objtype=None):
"Simulate func_descr_get() in Objects/funcobject.c"
if obj is None:
return self
return types.MethodType(self, obj)
class StaticMethod(object):
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
return self.f
我的问题是:当在最后一行访问self.f 时,f 本身不会被识别为描述符(因为每个函数都是非数据描述符)并因此绑定到 self,即一个静态方法对象?
【问题讨论】:
标签: python python-decorators python-descriptors