Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

python - How do I keep track of how an instance attribute's value is changed across multiple methods? Python3

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two problems with this function:

def thing1(self, x, y):
    x += 5
    y += 10
    print(x, y)
  1. You seem to actually want to modify the object's attributes self.x and self.y, but you are only modifying some temporary local variables x an y.
  2. You are passing 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...