[Python] implements public attributes of Python classes

Source: Internet
Author: User
Background today, someone asked Python if the class has a feature similar to the public attribute, that is, it modifies the corresponding attribute of an instance, and the corresponding attribute of all instances of this class is modified accordingly, I thought about using a helper Singleton mode class to solve the problem. Thinking about modifying one instance and another instance also follows the background...

Today, I was asked if the Python class has a feature similar to the public attribute, that is, it modifies the corresponding attribute of an instance, and the corresponding attribute of all instances of this class is modified accordingly, I thought about using a helper Singleton mode class to solve the problem.

Ideas

Modifying one instance and another instance also changes. it sounds like a singleton mode, but it only applies to one attribute, so you can borrow a secondary class.

Code
Class Attr (): attr = {} def _ init _ (self): self. _ dict _ = self. attrclass Myclass (): def _ init _ (self): self. attr = Attr () @ property def value (self): return self. attr. value @ value. setter def value (self, value): self. attr. value = value
Demo
In [47]: a = Myclass () In [48]: B = Myclass () In [49]:. value = 1In [50]: B. valueOut [50]: 1In [51]: B. value = 2In [52]:. value, B. valueOut [52]: (2, 2)
Feelings

Make full use of the design patterns and their combinations.

For more articles about public attributes of Python classes in [Python], refer to PHP Chinese network!

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.