Fix Python – How to return a value from __init__ in Python?


Asked By –

I have a class with an __init__ function.

How can I return an integer value from this function when an object is created?

I wrote a program, where __init__ does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So far, I declared a variable outside class. and setting it one function doesn’t reflect in other function ??

Now we will see solution for issue: 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

This question is answered By – Can Berk Güder

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0