是否必须在def __init__中声明所有Python实例变量? [英] Must all Python instance variables be declared in def __init__?

查看:172
本文介绍了是否必须在def __init__中声明所有Python实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还是可以用其他方式声明它们?

Or can they be declared otherwise?

下面的代码不起作用:

class BinaryNode():
    self.parent = None
    self.left_child = None

是否需要在__init__中声明它们?

Do they need to be declared in __init__?

推荐答案

不必在__init__中声明它们,但是为了使用self设置实例变量,需要引用self,而您定义变量的位置则没有.

They do not have to be declared in __init__, but in order to set an instance variable using self, there needs to be a reference to self, and the place you are defining the variables does not.

但是,

class BinaryNode():
    parent = None
    left_child = None

    def run(self):
        self.parent = "Foo"
        print self.parent
        print self.left_child

输出将为

Foo
None

要在评论中回答您的问题,是的.在我的示例中,您可以说:

To answer your question in the comment, yes. You can, in my example say:

bn = BinaryNode()
bn.new_variable = "Bar"

或者,正如我所展示的,您可以设置一个类级别的变量.该类的所有新实例将在实例化时获得类级别变量的副本.

Or, as I showed, you can set a class level variable. All new instances of the class will get a copy of the class level variables at instantiation.

也许您不知道可以将参数传递给构造函数:

Perhaps you are not aware that you can pass arguments to the constructor:

class BinaryNode(object):

    def __init__(self, parent=None, left_child=None):
        self.parent = parent
        self.left_child = left_child



bn = BinaryNode(node_parent, node_to_the_left)

这篇关于是否必须在def __init__中声明所有Python实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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