Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Class variables mutable? [duplicate]

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?

like image 798
pindakaas Avatar asked Jun 15 '17 09:06

pindakaas


1 Answers

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).

like image 61
Uriel Avatar answered Sep 27 '22 21:09

Uriel