web*_*org 88 python class init
我有一个__init__功能的类.
如何在创建对象时从此函数返回整数值?
我写了一个程序,__init__命令行解析在哪里,我需要设置一些值.可以在全局变量中设置它并在其他成员函数中使用它吗?如果是这样怎么办?到目前为止,我在课外宣布了一个变量.并设置一个功能不反映在其他功能??
Jac*_*zny 107
你为什么想这么做?
如果要在调用类时返回其他对象,请使用以下__new__()方法:
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return 42
obj = MyClass()
print obj
Run Code Online (Sandbox Code Playgroud)
Can*_*der 103
__init__需要返回None.你不能(或至少不应该)返回别的东西.
尝试制作任何想要返回实例变量(或函数)的内容.
>>> 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
Run Code Online (Sandbox Code Playgroud)
nos*_*klo 37
来自以下文件__init__:
作为构造函数的特殊约束,不能返回任何值; 这样做会导致在运行时引发TypeError.
作为证明,这段代码:
class Foo(object):
def __init__(self):
return 2
f = Foo()
Run Code Online (Sandbox Code Playgroud)
给出了这个错误:
Traceback (most recent call last):
File "test_init.py", line 5, in <module>
f = Foo()
TypeError: __init__() should return None, not 'int'
Run Code Online (Sandbox Code Playgroud)
PMN*_*PMN 16
样本使用的问题可能如下:
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)
Run Code Online (Sandbox Code Playgroud)
我没有足够的声誉所以我不能发表评论,这太疯狂了!我希望我能把它作为对weronika的评论发表
qua*_*ana 13
__init__在缺少return语句的情况下,该方法与其他方法和函数一样,默认情况下返回None,因此您可以像以下任一方式一样编写它:
class Foo:
def __init__(self):
self.value=42
class Bar:
def __init__(self):
self.value=42
return None
Run Code Online (Sandbox Code Playgroud)
但是,当然,添加return None不会给你带来什么.
我不确定你在追求什么,但你可能对以下其中一个感兴趣:
class Foo:
def __init__(self):
self.value=42
def __str__(self):
return str(self.value)
f=Foo()
print f.value
print f
Run Code Online (Sandbox Code Playgroud)
打印:
42
42
Run Code Online (Sandbox Code Playgroud)
您可以将其设置为类变量并从主程序中读取它:
class Foo:
def __init__(self):
#Do your stuff here
self.returncode = 42
bar = Foo()
baz = bar.returncode
Run Code Online (Sandbox Code Playgroud)