什么是wrapper_descriptor,为什么此情况下Foo.__init__()是一个?

15 投票
1 回答
5383 浏览
提问于 2025-04-17 19:41
import inspect

class Foo(object):
    pass

if __name__ == '__main__':
    print type(Foo.__init__)
    print inspect.getsourcelines(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__呢?

1 个回答

10

你遇到的问题其实是一个实现细节。这种情况在用C语言实现的类中很常见,比如object就是这样。这里提到的不是Python的方法,而是C语言的方法,而这个包装器是这个接口的一部分。

那为什么类字典里会有一个__init__呢?

其实它不在类字典里,而是在object字典里。object里有一个__init__,这样当你用super()去调用你类的基类的__init__方法时,就不会出错了。

撰写回答