pythonclassinit

How to return a value from __init__ in Python?


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 ??


Solution

  • __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