我有一个带有__init__
函数的类。
创建对象时,如何从该函数返回整数值?
我写了一个程序,__init__
命令行解析在哪里,我需要设置一些值。可以将其设置在全局变量中并在其他成员函数中使用吗?如果是这样怎么做?到目前为止,我在类外声明了一个变量。并将其设置为一个功能不会反映在其他功能中??
你为什么想这么做?
如果要在调用类时返回其他对象,请使用以下__new__()
方法:
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return 42
obj = MyClass()
print obj
__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
从以下文档__init__
:
作为对构造函数的特殊约束,不能返回任何值;这样做会导致在运行时引发 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)
该__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
。
您可以将其设置为类变量并从主程序中读取它:
class Foo:
def __init__(self):
#Do your stuff here
self.returncode = 42
bar = Foo()
baz = bar.returncode
class Solve:
def __init__(self,w,d):
self.value=w
self.unit=d
def __str__(self):
return str("my speed is "+str(self.value)+" "+str(self.unit))
ob=Solve(21,'kmh')
print (ob)
输出:我的速度是 21 kmh
我们不能从 init 返回值。但是我们可以使用new返回值。
class Car:
def __new__(cls, speed, unit):
return (f"{speed} with unit {unit}")
car = Car(42, "km")
print(car)
只是想添加,你可以返回类__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
上述方法可帮助您对测试中的异常执行特定操作
这里的解决方案 是的,尝试从 python 中的init方法返回会返回错误,因为它是类的构造函数,您只能为类的范围赋值,但不能返回特定值。如果你想返回一个值但不想创建一个方法,你可以使用 str方法
def __init__(self,a):
self.value=a
def __str__(self):
return str("all my return values are possible here")`
好吧,如果您不再关心对象实例......您可以替换它!
class MuaHaHa():
def __init__(self, ret):
self=ret
print MuaHaHa('foo')=='foo'