0

I'm trying to teach a reason for the need of instance variables and using self. So I came up with the following example. However, it's not going the way I thought it would, haha. I have come to appeal to you all to answer my question: although I am changing the class variable, how come the last print statement with x.one doesn't print out -1 as well?

class example():
  one = 1
  two = 2

# Creating 2 'example' objects, x and y
x = example()
y = example()
print("x is: ", x.one, "y is: ", y.one) # output: x is 1, y is 1

# From the print statement, we'll see that changing one class object does not affect another class object
x.one = 0
print("x is: ", x.one, "y is: ", y.one) # output: x is 0, y is 1

# But what if we changed the class itself?
example.one = -1
print("x is: ", x.one, "y is: ", y.one) # output: x is 0, y is -1

My guess is that it has something to do with me altering x.one's value in the block above, which makes x.one possibly having a new location in memory instead of referencing example.one's location in memory.

If you could give me a more detailed reason, I would very much appreciate it and would be able to pass on the knowledge to my student.

1 Answer 1

2

When you started, there were no instance attributes defined, just the class attributes one and two. So when you ask the instances x and y for their attribute one, they first check to see if they have an instance attribute, see that they do not, and thus report the class attribute.

     Instance    Class
x                 *1*
y                 *1*

When you assigned to x.one, this created an instance attribute called one on the instance x. So when you ask them again, this time x reports its own instance value of one. y still reports the class attribute.

     Instance    Class
x      *0*         1
y                 *1*

When you then change the class attribute one, this doesn't change x because its instance attribute one still takes precedence over the class attribute. You see the difference in y, because it still doesn't have any instance attribute and thus continues to report the class attribute.

     Instance    Class
x      *0*        -1
y                *-1*
Sign up to request clarification or add additional context in comments.

1 Comment

I dig it. Thanks for the examples, too. Just for my personal knowledge, is this explanation similar to my guess, but more at the "programming level" as opposed to the "memory level"?

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.