[英]isinstance(list.append (BuiltinFunctionType, BuiltinMethodType)) == False
在非内置类型上, types.FunctionType
和types.MethodType
表现如预期:
>>> isinstance(MyClass.func, FunctionType)
True
>>> isinstance(MyClass.func, MethodType)
False
>>> isinstance(MyClass().func, FunctionType)
False
>>> isinstance(MyClass().func, MethodType)
True
但是,在内置类型上, BuiltinFunctionType
和BuiltinMethodType
没有相应的行为:
>>> isinstance(list.append, (FunctionType, MethodType,
... BuiltinFunctionType, BuiltinMethodType))
False <- Why??
>>> isinstance([].append, (FunctionType, MethodType))
False
>>> isinstance([].append, BuiltinFunctionType)
True <- Why??
>>> isinstance([].append, BuiltinMethodType)
True
现在这没有意义,不是吗? 有人可以解释吗?
编辑: isinstance(list.append, MethodDescriptorType) == True
。 有人可以解释MethodDescriptorType
与BuiltinMethodType
不同以及我们为什么需要它? 官方文档并没有说太多。
BuiltinFunctionType
和BuiltinMethodType
只是指同一个 object 的不同名称:
>>> BuiltinFunctionType is BuiltinMethodType
True
isinstance(list.append, BuiltinMethodType)
为假,因为它不是方法(即绑定到某个对象的实例方法)。 方法绑定通过object.__getattribute__
发生,因此使用 class 定义的函数只是普通函数:
>>> def func(x): pass
...
>>> class MyClass: func = func
...
>>> MyClass.func is func
True
因此isinstance(MyClass.func, FunctionType)
。 这是有效的,因为所有函数都是非数据描述符:
>>> func.__get__
<method-wrapper '__get__' of function object at 0x7f80abe57400>
对于内置类型,这些对象(例如list.append
)也是处理与其对象的绑定的专用描述符。 所以x = []; x.append
x = []; x.append
返回一个由描述符list.append
创建并绑定到 object x
的绑定方法:
>>> type(list.append)
<class 'method_descriptor'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.