8

If I define a simple class

class someClass():
    var = 1

x = someClass()
someClass.var = 2

This will make x.var equal 2. This is confusing to be because normally something akin to this like:

a = 1
b = a
a = 2

will leave b intact as b==1. So why is this not the same with class variables? Where is the difference? Can call all class variables mutable? In a way the class variables work more like assigning a list to a=[1] and doing a[0]=2.

Basically the problem is how is x.var acessing someClass.var it must be something different then is used when two variables are set equal in python. What is happening?

18
  • 2
    now set x.var = 3 and see what happens to someClass.var Commented Jun 15, 2017 at 9:18
  • I know but thats not the point Commented Jun 15, 2017 at 9:19
  • 1
    No, that is the point. Essentially, when you do SomeClass.var and someInstance.var are not necessarily same thing. Commented Jun 15, 2017 at 9:20
  • not at all this is about the fact that someClass.var = 2 changes x.var and how x.var is bound to the class variable compared to the normal functioning of variables in python Commented Jun 15, 2017 at 9:21
  • 1
    A picture is worth a thousand words: stackoverflow.com/a/34126204/476 Commented Jun 15, 2017 at 9:28

1 Answer 1

3

var is a static class variable of someClass.

When you reach out to get x.var, y.var or some_other_instance.var, you are accessing the same variable, not an instance derived one (as long as you didn't specifically assigned it to the instance as a property).

Sign up to request clarification or add additional context in comments.

2 Comments

So then when I use x.var = 2 I basically create a new variable in x that shadows the variable in someClass in this instance?
@pindakaas Bingo!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.