Python class instance attributes and attribute appreciated

Logically speaking, to change the class attribute, instance of this object class attribute should also be changed, but in python actually not the case

class test():
    name = 111

a = test()
b = test()

a.name = 222
test.name = 333
print(a.name,b.name,test.name)

输出:
222 333 333

A.name value here is not changed test.name = 333

View property location in memory

print(id(a.name))
print(id(b.name))
print(id(test.name))

输出:
140705896729248
2154539206672
2154539206672

Then view the properties of an object

print(a.__dict__)
print(b.__dict__)
print(test.__dict__)

{'name': 222}
{}
{...'name': 333.....}

So when operating a property assignment object to the name, creating a name attribute can be understood as the name is not the type of property but the property of a target (good about)

b was not created, so (the same memory location) when the query is actually when b.name investigation test.name

So priority class attributes and attribute query for instance: Instance Properties> Properties class instance attribute is not going to check the class attribute

 

Guess you like

Origin www.cnblogs.com/fengf233/p/10991028.html