什么是 wrapper_descriptor,为什么 Foo.__init__() 在这种情况下是其中之一?

2022-01-18 00:00:00 python initialization

问题描述

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

Google 几乎没有提供关于 wrapper_descriptor 究竟是什么以及为什么空类有一个不是方法而是 wrapper_descriptor 的 __init__ 方法的有用信息.

Googling gives very little useful information about what, exactly, a wrapper_descriptor is, and why an empty class has an __init__ method that is not a method, but rather a wrapper_descriptor.

这里到底发生了什么?没有 __init__ 方法的所有类都具有这些 wrapper_descriptor 事物之一吗?为什么类字典中有一个 __init__?

What exactly is going on here? Do all classes without __init__ methods have one of these wrapper_descriptor things? Why is there an __init__ in the class dict at all?


解决方案

你遇到的是一个实现细节.这对于用 C 实现的类来说是非常典型的,就像 object 一样.它不是 Python 方法,而是 C 方法,包装器是该接口的一部分.

What you've run into is an implementation detail. This is pretty typical for classes implemented in C, as object is. It's not a Python method, it is a C method, and the wrapper is part of this interface.

为什么类字典中有一个 __init__?

Why is there an __init__ in the class dict at all?

它不在类字典中,它在 object 字典中.object 有一个 __init__ ,因此当您尝试使用 super() 调用类的基类的 __init__ 方法时,它不会失败.

It's not in the class dict, it's in the object dict. object has an __init__ so that when you try to call your class's base classes' __init__ methods using super(), it doesn't fail.

相关文章