必须在def __init__中声明所有Python实例变量吗?

aer*_*ain 7 python instance-variables

或者他们可以另外声明?

以下代码不起作用:

class BinaryNode():
    self.parent = None
    self.left_child = None
Run Code Online (Sandbox Code Playgroud)

他们需要申报__init__吗?

sbe*_*rry 12

它们不必声明__init__,但为了使用设置实例变量self,需要引用self,而您定义变量的地方则不需要.

然而,

class BinaryNode():
    parent = None
    left_child = None

    def run(self):
        self.parent = "Foo"
        print self.parent
        print self.left_child
Run Code Online (Sandbox Code Playgroud)

输出将是

Foo
None
Run Code Online (Sandbox Code Playgroud)

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

bn = BinaryNode()
bn.new_variable = "Bar"
Run Code Online (Sandbox Code Playgroud)

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

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

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)
Run Code Online (Sandbox Code Playgroud)