How to return a value from __init__ in Python?

2020-01-24 11:08发布

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条回答
可以哭但决不认输i
2楼-- · 2020-01-24 11:52

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'
查看更多
手持菜刀,她持情操
3楼-- · 2020-01-24 11:55

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
查看更多
Melony?
4楼-- · 2020-01-24 11:57

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

查看更多
男人必须洒脱
5楼-- · 2020-01-24 11:58

__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
查看更多
时光不老,我们不散
6楼-- · 2020-01-24 11:59

You can just set it to a class variable and read it from the main program:

class Foo:
    def __init__(self):
        #Do your stuff here
        self.returncode = 42
bar = Foo()
baz = bar.returncode
查看更多
贼婆χ
7楼-- · 2020-01-24 12:02

Well, if you don't care about the object instance anymore ... you can just replace it!

class MuaHaHa():
def __init__(self, ret):
    self=ret

print MuaHaHa('foo')=='foo'
查看更多
登录 后发表回答