什么是wrapper_descriptor,在这种情况下为什么是Foo .__ init __()?
问题描述:
import inspect
class Foo(object):
pass
if __name__ == '__main__':
print type(Foo.__init__)
print inspect.getsourcelines(Foo.__init__)
输出:什么是wrapper_descriptor,在这种情况下为什么是Foo .__ init __()?
<type 'wrapper_descriptor'>
Traceback (most recent call last):
*snip*
File "/usr/lib/python2.7/inspect.py", line 420, in getfile
'function, traceback, frame, or code object'.format(object))
TypeError: <slot wrapper '__init__' of 'object' objects> is not a module, class, method, function, traceback, frame, or code object
谷歌搜索提供了究竟,一个wrapper_descriptor是什么,很少有用的信息,为什么一个空类有一个__init__
方法不是方法,而是wrapper_descriptor。
这里究竟发生了什么?没有__init__
方法的所有课程都有这些wrapper_descriptor的东西之一吗?为什么在班级字典中有__init__
?
答
你碰到的是一个实现细节。这对于在C中实现的类非常典型,因为object
是。它不是一个Python方法,它是一个C方法,包装器是这个接口的一部分。
为什么在dict类中有
__init__
?
这不是在类字典中,它在object
字典中。 object
有一个__init__
,因此当您尝试使用super()
调用您的类的基类“__init__
”方法时,它不会失败。
如果您在意,C API文档将解释除此之外的一些细节。但通常你并不关心“插槽包装器”,“方法包装器”等类似的东西,你可以调用它们,就好像它们是绑定方法,未绑定方法等一样,但是没有任何Python源代码。 – abarnert 2013-03-19 23:38:32