[Python] implements the common properties of the Python class

Source: Internet
Author: User

Background

Today, I see someone asking if a Python class has an attribute that is similar to a public property, which modifies the corresponding property of an instance, modifies the corresponding properties of all instances of the class, and then thinks that a class that uses an auxiliary singleton pattern solves the problem.

Ideas

Modifying an instance Another instance is also modified, which sounds like a singleton pattern, but only for one property, so you can borrow a helper 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

Demonstrate

In [the]: a = Myclass () in [1In]: b = Myclass () in [B.value]: A.value = 1In []: b.valueout[50]: []: A.V = 2In []: Alue, b.valueout[52]: (2, 2)

Feelings

Design patterns and their combinations are utilized.

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.