2

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, you can run node.left = 10 and every node instance would have a.left == 10 (if you are using the first code chunk).
The values in the first class will be available when instantiated. They can even be set independently of the class values. So other than accessing them without instantiation both classes are more or less the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.