Reputation: 5
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?
Upvotes: 0
Views: 58
Reputation: 24232
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.
Upvotes: 2
Reputation: 4215
You have to create an object of your class:
tree = Tree(0)
tree.get_rank()
tree.set_rank(5)
tree.get_rank()
5
Upvotes: 1