如何从Python中的__init__返回值? [英] How to return a value from __init__ in Python?
问题描述
我有一个类带有 __ init __
函数。
I have a class with an __init__
function.
如何在创建对象时从此函数中返回整数值?
How can I return an integer value from this function when an object is created?
,其中 __ init __
执行命令行解析,我需要设置一些值。是否设置它在全局变量和使用它在其他成员函数?如果是这样怎么办呢?到目前为止,我在类外声明了一个变量。并设置一个函数不反映在其他函数中
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 ??
推荐答案
__ init __
返回新创建的对象。您不能(或至少不应该)返回其他内容。
__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
这篇关于如何从Python中的__init__返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!