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!