0

I'm trying to update the rank field in the node using setters in Python. Below is the code I've used:

class Tree(object):
    def __init__(self,u):
        self.parent=u
        self.rank=0

    def get_parent(self):
        return self.parent

    def get_rank(self):
        return self.rank

    def set_parent(self,v):
        self.parent=v

    def set_rank(self,v):
        self.rank=v

And then I'm running the following code:

Tree(0).get_rank()
Tree(0).set_rank(5)
Tree(0).get_rank()

Output:

0

Expected Output:

5

Here, the output I'm getting is 0 itself instead of 5 which I'm expecting. Can anybody let me know where exactly am I going wrong in the code or even conceptually?

2
  • 2
    Tree(0) on 2nd line is not same reference as Tree(0) on 1st line. Try doing id(Tree(0)) for both lines to see it. Commented Nov 11, 2019 at 7:44
  • You are performing your operations on a new object each time, so you're throwing away your intermediate state. Besides, getters and setters are very common in Java, but are very uncommon in Python. Just set and read the attributes directly Commented Nov 11, 2019 at 7:44

2 Answers 2

2

You are creating and using a new Tree object on each line:

Tree(0).get_rank()   # first tree object
Tree(0).set_rank(5)  # second tree object
Tree(0).get_rank()   # third tree object

So, when you call get_rank on the third one, it's freshly initialized, so its rank is 0.

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

Comments

1

You have to create an object of your class:

tree = Tree(0)
tree.get_rank()
tree.set_rank(5)
tree.get_rank()
5

Comments

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.