Reputation: 352
I am new to Python and I am learning object oriented programming. However, I have one question which I cannot find the answer to anywhere
Assume that I have the example below:
class Node:
def __init__(self):
self.x1 = 10
self.y1 = 100
def thing1(self, x, y):
x += 5
y += 10
print(x, y)
def thing2(self, x, y):
x += 10
print(x)
node = Node()
def main():
node.thing1(node.x1, node.y1)
node.thing2(node.x1, node.y1)
main()
The output I get when I run this code is the following:
15 110
20
But the output I wanted to get was:
15 110
25
For some reason python does not track how the value of the instance variable is changed across multiple methods
I know that I can just change the value to the instance attribute directly in the method and that will work, but I am curious to the solution to this problem in the example I provided above.
I would greatly appreciate it if you could help me with this issue because it has been puzzling me for quite some time.
Upvotes: 0
Views: 74
Reputation: 19402
There are two problems with this function:
def thing1(self, x, y):
x += 5
y += 10
print(x, y)
self.x
and self.y
, but you are only modifying some temporary local variables x
an y
.x
and y
values, although they are not needed.You have the same problems with the other function as well.
This would be the corrected code:
class Node:
def __init__(self):
self.x = 10
self.y = 100
def thing1(self):
self.x += 5
self.y += 10
print(self.x, self.y)
def thing2(self):
self.x += 10
print(self.x)
def main():
node = Node()
node.thing1()
node.thing2()
if __name__ == "__main__":
main()
Upvotes: 1