How to return a value from __init__ in Python?
__init__
is required to return None. You cannot (or at least shouldn't) return something else.
Try making whatever you want to return an instance variable (or function).
>>> 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
From the documentation of __init__
:
As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.
As a proof, this code:
class Foo(object): def __init__(self): return 2f = Foo()
Gives this error:
Traceback (most recent call last): File "test_init.py", line 5, in <module> f = Foo()TypeError: __init__() should return None, not 'int'