如何从 Python 中的 __init__ 返回一个值? [英] How to return a value from __init__ in Python?

查看:35
本文介绍了如何从 Python 中的 __init__ 返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 __init__ 函数的类.

如何在创建对象时从此函数返回整数值?

我写了一个程序,其中 __init__ 执行命令行解析,我需要设置一些值.可以将其设置在全局变量中并在其他成员函数中使用吗?如果是这样怎么办?到目前为止,我在类外声明了一个变量.并设置它一个功能不会反映在其他功能中??

解决方案

__init__ 需要返回 None.您不能(或至少不应该)返回其他东西.

尝试制作任何你想要返回的实例变量(或函数).

<预><代码>>>>Foo类:... def __init__(self):...返回 42...>>>foo = foo()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:__init__() 应该返回 None

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 ??

解决方案

__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

这篇关于如何从 Python 中的 __init__ 返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆