python class variables not getting changed for all the instances? -


i realized python class variables have same memory location instances, not getting why changing class variable 1 of instance don't affect other instances , class itself? please see following code below:

class (object):     name = 'donald '     def __init__(self):         self.x = 4 c = sam() z = sam() print hex(id(c.name)), hex(id(z.name)), hex(id(sam.name)) print c.name, z.name  c.name = 'trump' print c.name, z.name, us_president.name print hex(id(c.name)), hex(id(z.name)), hex(id(us_president.name))  us_president.name = 'obama' print c.name, z.name, us_president.name   output: 0x7f227776a930 0x7f227776a930 0x7f227776a930 donald donald trump donald donald 0x7f227776a420 0x7f227776a930 0x7f227776a930 trump obama obama 

can please explain behavior. in advance

if assign attribute of instance, name becomes instance variable. if there class variable of same name, becomes hidden in particular instance, still accessible in other instances of class. if want modify class variable, have assign on class, not instance.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -