Must all Python instance variables be declared in def __init__?

aerain picture aerain · Sep 5, 2012 · Viewed 12.6k times · Source

Or can they be declared otherwise?

The code below does not work:

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

Do they need to be declared in __init__?

Answer

sberry picture sberry · Sep 5, 2012

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)