Search code examples
pythonclassinitialization

python class initialization


Folks,

I am wondering if the following two definitions of the node class are the same or not?

class node:
    left = None
    right= None
    def __init__(self, data):
        self.data = data


class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right= None

Thanks for letting me know.


Solution

  • No, they are not the same.

    In the second definition, node.left and node.right don't exist. The right and left attributes would only exist on an initialized instance of the class. However, in the first definition, you can access node.left and node.right directly on the class; you don't have to instantiate it.