我有一个具有__init__
功能的课程。
如何在创建对象时从此函数返回整数值?
我写了一个程序,其中__init__
执行命令行解析,我需要设置一些值。可以在全局变量中设置它并在其他成员函数中使用它吗?如果是这样怎么办?到目前为止,我在课外宣布了一个变量。并设置一个功能不反映在其他功能??
__init__
必须退回无。你不能(或至少不应该)返回别的东西。
尝试制作任何想要返回实例变量(或函数)的内容。
>>> 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
你为什么想这么做?
如果要在调用类时返回其他对象,请使用__new__()
方法:
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return 42
obj = MyClass()
print obj
作为构造函数的特殊约束,不能返回任何值;这样做会导致在运行时引发TypeError。
作为证明,这段代码:
class Foo(object):
def __init__(self):
return 2
f = Foo()
给出了这个错误:
Traceback (most recent call last):
File "test_init.py", line 5, in <module>
f = Foo()
TypeError: __init__() should return None, not 'int'
样本使用的问题可能如下:
class SampleObject(object)
def __new__(cls,Item)
if cls.IsValid(Item):
return super(SampleObject, cls).__new__(cls)
else:
return None
def __init__(self,Item)
self.InitData(Item) #large amount of data and very complex calculations
...
ValidObjects=[]
for i in data:
Item=SampleObject(i)
if Item: # in case the i data is valid for the sample object
ValidObjects.Append(Item)
我没有足够的声誉所以我不能发表评论,这太疯狂了!我希望我能把它作为对weronika的评论发表
与其他方法和函数一样,__init__
方法在缺少return语句的情况下默认返回None,因此您可以像以下任何一种一样编写它:
class Foo:
def __init__(self):
self.value=42
class Bar:
def __init__(self):
self.value=42
return None
但是,当然,添加return None
不会给你买任何东西。
我不确定你在追求什么,但你可能对以下其中一个感兴趣:
class Foo:
def __init__(self):
self.value=42
def __str__(self):
return str(self.value)
f=Foo()
print f.value
print f
打印:
42
42
__init__
不返回任何东西,应该总是返回None
。
只想添加,你可以返回__init__
中的类
@property
def failureException(self):
class MyCustomException(AssertionError):
def __init__(self_, *args, **kwargs):
*** Your code here ***
return super().__init__(*args, **kwargs)
MyCustomException.__name__ = AssertionError.__name__
return MyCustomException
上述方法可帮助您在测试中对异常执行特定操作
您可以将其设置为类变量并从主程序中读取它:
class Foo:
def __init__(self):
#Do your stuff here
self.returncode = 42
bar = Foo()
baz = bar.returncode
好吧,如果你不再关心对象实例......你可以替换它!
class MuaHaHa():
def __init__(self, ret):
self=ret
print MuaHaHa('foo')=='foo'