[PYTHON] Globalization of class instance variables

Let's create a class instance variable with the Python Singleton pattern so that it can be used like a global variable.


singleton01.py


class MySingleton(object):
    __obj = None
    __init_flg = True

    def __new__(cls, *args, **kwargs):
        if cls.__obj is None:
            cls.__obj = super().__new__(cls, *args)
        return cls.__obj

    def __init__(self):
        if self.__init_flg:
            self._x = 0
            self.__init_flg = False  #Do not initialize after the second time

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value


def use_singleton1():
    print('↓--------use_singleton1')
    a1 = MySingleton()
    print('MySingleton(a1) property x = {}'.format(a1.x))
    a1.x = 150
    print('MySingleton(a1) property x = {}'.format(a1.x))
    print(a1)


def use_singleton2():
    print('↓--------use_singleton2')
    b1 = MySingleton()
    print('MySingleton(b1) property x = {}'.format(b1.x))
    b1.x = 250
    print('MySingleton(b1) property x = {}'.format(b1.x))
    print(b1)


use_singleton1()
use_singleton2()

Execution result: ↓--------use_singleton1 MySingleton(a1) property x = 0 MySingleton(a1) property x = 150 <main.MySingleton object at 0x00000000010C22B0> ↓--------use_singleton2 MySingleton(b1) property x = 150 MySingleton(b1) property x = 250 <main.MySingleton object at 0x00000000010C22B0>


It may be convenient to use the @decorator function to create multiple singleton pattern classes

singleton02.py


def singleton(cls, *args, **kwargs):
    obj = None

    def wrapper():
        nonlocal obj
        if obj is None:
            obj = cls(*args, **kwargs)
        return obj
    return wrapper

@singleton
class MySingleton(object):
    __init_flg = True

    def __init__(self):
        if self.__init_flg:
            self._x = 0
            self.__init_flg = False  #Do not initialize after the second time

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

@singleton
class MySingleton2(object):
    pass


a = MySingleton()
a.x = 11
b = MySingleton()
print('MySingleton(b) property x = {}'.format(b.x))
b.x = 12
print('MySingleton(a) property x = {}'.format(a.x))
print('MySingleton(b) property x = {}'.format(b.x))
print(a)
print(b)
print('----------------------------------------------------------')
a2 = MySingleton2()
b2 = MySingleton2()
print(a2)
print(b2)

Execution result: MySingleton(b) property x = 11 MySingleton(a) property x = 12 MySingleton(b) property x = 12 <main.MySingleton object at 0x0000000000B820B8> <main.MySingleton object at 0x0000000000B820B8> ---------------------------------------------------------- <main.MySingleton2 object at 0x0000000000B821D0> <main.MySingleton2 object at 0x0000000000B821D0>


Recommended Posts

Globalization of class instance variables
Python: Class and instance variables
Python class variables and instance variables
Class variables
Class variables
Reference order of class variables and instance variables in "self. Class variables" in Python
[Python] class, instance
Example of using class variables and class methods
[python] Get a list of instance variables
Python class, instance
About Class and Instance
parallelization of class method
Declaration of C global variables
Create an instance of a predefined class from a string in Python
I was addicted to confusing class variables and instance variables in Python
Use instance method and class method properly
[Python of Hikari-] Chapter 09-03 Class (inheritance)
Landmines hidden in Python class variables
Python class definitions and instance handling
Calculation of homebrew class and existing class
How should I access class variables?
[Python] Inherit a class with class variables
Hit a method of a class instance with the Python Bottle Web API