Python classes and class instances are mutable objects that can be assigned values at any time and modified in place.
You need to be particularly careful when modifying class properties, because all class instances inherit shared class properties, unless the instance itself has a property with the same name as the Class property. Modifying a class property affects all instances generated by this class.
classCA (object): Cls_pre='AAAAA' def __init__(self): Self.obj_pre='bbbbb'a=CA () b=CA ()Print(A.cls_pre, A.obj_pre)Print(B.cls_pre, b.obj_pre) Ca.cls_pre='CCCCC'C=CA () d=CA () D.cls_pre='ddddd'Print(A.cls_pre, A.obj_pre)Print(B.cls_pre, B.obj_pre)Print(C.cls_pre, C.obj_pre)Print(D.cls_pre, D.obj_pre)
Operation Result:
AAAAA bbbbbaaaaa bbbbbccccc bbbbbccccc BBBBBCCCCC bbbbbddddd bbbbb
Code, the Class property Ca.cls_pre is re-assigned as ' CCCCC '. After modifying the class properties, not only the cls_pre of the class instance C that is subsequently created changes, but the class attribute cls_pre of the class instance A and B that were created before the class properties were modified.
Therefore, when you modify a class property outside the class statement, the class properties of all instances created by this class are changed, because all instances share the class attribute Ca.cls_pre. Unless the instance itself has an instance property of the same name, the class property is overwritten, such as D.cls_pre = ' ddddd ' in the code.
Carefully modify the class properties of Python