Home > Backend Development > Python Tutorial > [Python] Implement public properties of Python classes

[Python] Implement public properties of Python classes

高洛峰
Release: 2017-02-16 11:30:44
Original
1492 people have browsed it

Background

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.

Idea

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.

Code

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
Copy after login

Demo

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)
Copy after login

Impression

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template