tags:

views:

572

answers:

5

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

+9  A: 

__init__ returns the newly created object. 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
Can Berk Güder
+1: You **cannot** return something else. It doesn't make any sense.
S.Lott
+3  A: 

__init__ doesn't return anything and should always return None.

gruszczy
+5  A: 

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 2

f = 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'
nosklo
+4  A: 

Why would you want to do that?

If you want to return some other object when a class is called, then use the __new__() method:

class MyClass(object):
    def __init__(self):
        print "never called in this case"
    def __new__(cls):
        return 42

obj = MyClass()
print obj
Jacek Konieczny
+1  A: 

The __init__ method, like other methods and functions returns None by default in the absence of a return statement, so you can write it like either of these:

class Foo:
    def __init__(self):
        self.value=42

class Bar:
    def __init__(self):
        self.value=42
        return None

But, of course, adding the return None doesn't buy you anything.

I'm not sure what you are after, but you might be interested in one of these:

class Foo:
    def __init__(self):
        self.value=42
    def __str__(self):
        return str(self.value)

f=Foo()
print f.value
print f

prints:

42
42
quamrana
ohh..Can i access member variable out the class ? Then that should solve my issue ....thanks
lakshmipathi
@lakshmipathi, Yes, instance variables like this are public.
quamrana