Bringe Bringe - 3 months ago 10
Python Question

Strange behaviour of Class instance - when updating internal variables

Let's say I define the following class in Python.

class test():
def __init__(self):
self.x = 0
self.y = self.x ** 2
def check(self):
self.x = self.x + 1
print self.x
print self.y


Here I have two internal variables x and y. In the initialization I have set $$ y = x^2 $$. Now each time I call the method
check()
it increments the value of x by 1 :
self.x = self.x + 1
. However when I print the values x correctly increments by 1 but y remains 0 always. (Should'nt it be x^2??) What's going wrong?

Answer

Your self.y is only assigned when you first create an instance of your class. It is not updated every time you call a function. The def __init__(self): function is only executed when you do
myVar = new test(), therefore the value of y is only assigned and updated once.

Your code would need to be:

class test():
    def __init__(self):
        self.x = 0
        self.y = self.x ** 2
    def check(self):
        self.x = self.x + 1
        self.y = self.x ** 2
        print self.x
        print self.y