Carefully modify the class properties of Python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.