Skip to main content
 首页 » 编程设计

python之为什么 python 的 __init__ 函数没有返回语句,即使它是一个函数

2025年05月04日23luoye11

这可能是个愚蠢的问题,但我很想知道答案。 根据官方文档,__init__ 不需要 return 语句。任何特定的原因。

>>> class Complex: 
...     def __init__(self, realpart, imagpart): 
...         self.r = realpart 
...         self.i = imagpart 
... 
>>> x = Complex(3.0, -4.5) 
 
>>> x.r, x.i 
(3.0, -4.5) 

请您参考如下方法:

__init__() 不是一个普通函数。它是 Python 用来自定义类实例的一种特殊方法。它是 Python's data model 的一部分:

Called after the instance has been created (by __new__()), but before it is returned to the caller[...].

从上面可以看出,当你创建一个类的新实例时,Python首先调用__new_()——这也是一个特殊的方法——来创建一个类的新实例。然后调用 __init__() 来自定义新实例。

从 __init__() 返回任何东西是没有意义的,因为类实例已经创建。事实上,Python 甚至会引发错误来防止这种情况发生:

>>> class A: 
...     def __init__(self): 
...         return 'foo' 
...  
>>> A() 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: __init__() should return None, not 'str' 
>>>  

如果你想知道幕后到底发生了什么,@eryksun提供了一个很好的解释:

To completely explain this story, you have to step back to the metaclass __call__ method. In particular the default type.__call__ in CPython calls __new__ and __init__ via their C slot functions, and it's slot_tp_init (defined in Objects/typeobject.c) that enforces the return value to be None. If you use a custom metaclass that overrides type.__call__, it can manually call the __new__ and __init__ methods of the class with no restriction on what __init__ can return -- as silly as that would be.