如何在Python中从__init__返回值?
我有一个类里面有一个 __init__
函数。
我想在创建对象的时候,从这个函数返回一个整数值,应该怎么做呢?
我写了一个程序,在里面 __init__
函数负责处理命令行输入,我需要设置一个值。把这个值放在全局变量里,然后在其他成员函数中使用,这样可以吗?如果可以的话,应该怎么做呢?到目前为止,我在类外面声明了一个变量,但在一个函数里设置这个变量的值,另一个函数却看不到这个变化,这是怎么回事呢?
14 个回答
45
作为构造函数的一个特殊限制,不能返回任何值;如果这样做,会在运行时引发TypeError错误。
作为证明,这段代码:
class Foo(object):
def __init__(self):
return 2
f = Foo()
会出现这个错误:
Traceback (most recent call last):
File "test_init.py", line 5, in <module>
f = Foo()
TypeError: __init__() should return None, not 'int'
211
如果你想在调用一个类的时候返回其他的对象,可以使用 __new__()
方法:
class MyClass:
def __init__(self):
print("never called in this case")
def __new__(cls):
return 42
obj = MyClass()
print(obj)
# Output: 42
171
__init__
是一个特殊的方法,它必须返回 None。你不能(或者说不应该)返回其他东西。
你可以试着把你想返回的内容变成一个实例变量(或者函数)。
>>> class Foo:
... def __init__(self):
... return 42
...
>>> foo = Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() should return None