クラスのインスタンス変数をグローバル変数と同じように使えるように、PythonのSingletonパターンで作成してみます。
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 # 2回目以後初期化されないように
@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()
実行結果:
↓--------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>
複数シングルトンパターンクラスを作成するには@デコレータ関数を利用すれば便利かもしれません
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 # 2回目以後初期化されないように
@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)
実行結果:
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>
※マルチスレッドの場合、[import threading]で排他制御する必要があります