Home > Article > Backend Development > [Python] Implement public properties of Python classes
Today I saw someone asking whether Python classes have characteristics similar to public attributes. That is, if the corresponding attributes of a certain instance are modified, the corresponding attributes of all instances of the class will be modified accordingly. I thought I thought about using an auxiliary singleton mode class to solve the problem.
Modify one instance and the other instance will also be modified accordingly. It sounds like the characteristics of the singleton mode, but it only targets one attribute, so you can borrow an auxiliary class.
class Attr(): attr = {} def __init__(self): self.__dict__ = self.attr class 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
In [47]: a = Myclass() In [48]: b = Myclass() In [49]: a.value = 1 In [50]: b.value Out[50]: 1 In [51]: b.value = 2 In [52]: a.value, b.value Out[52]: (2, 2)
Make use of design patterns and their combinations.
For more [Python] implementing public attributes of Python classes, please pay attention to the PHP Chinese website for related articles!