能否不每次调用都实例化MethodType来实现绑定方法?
关于Python类方法绑定实现的疑问
正如文档所述,类体中定义的函数会按需绑定到类实例(即当实例调用该函数时),函数对象是非数据描述符。实际运行结果确实符合这一描述:
>>> class X: ... def foo(self): 1 ... >>> x = X() >>> print(hex(id(x.foo))) # 0x7fe59020fa40 ... 几秒后 ... >>> print(hex(id(x.foo))) # 0x7fe59020fbc0 <- 地址不同! >>> print(x.foo is x.foo) # False
函数__get__的纯Python等效实现如下:
def __get__(self, instance, owner=None): "Simulate func_descr_get() in Objects/funcobject.c" if instance is None: return self return MethodType(self, instance)
那是否可以不创建MethodType实例,而是返回一个小型包装器来提升效率?对应的纯Python实现如下:
def __get__(self, instance, owner=None): "Simulate func_descr_get() in Objects/funcobject.c" def new_func(*args, **kwargs): return self(instance, *args, **kwargs) return new_func if instance is not None else self
当然这些逻辑在CPython中并非用纯Python编写,而是用C实现的,可能存在各种优化手段。但用C定义这种小型包装器是否比实例化MethodType更快?我好奇为何官方未采用这种方式,相比每次实例化MethodType,该方式存在哪些缺点?
内容的提问来源于stack exchange,提问作者battlecruiser_operational
相关产品推荐
相关产品推荐

