这可能是个愚蠢的问题,但我很想知道答案。 根据官方文档,__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 defaulttype.__call__in CPython calls__new__and__init__via their C slot functions, and it'sslot_tp_init(defined in Objects/typeobject.c) that enforces the return value to be None. If you use a custom metaclass that overridestype.__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.
