Must all Python instance variables be declared in def __init__?

后端 未结 4 2144
挽巷
挽巷 2021-01-02 05:36

Or can they be declared otherwise?

The code below does not work:

class BinaryNode():
    self.parent = None
    self.left_child = None
4条回答
  •  无人及你
    2021-01-02 05:56

    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.

    However,

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

    The output will be

    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)
    

提交回复
热议问题