Skip to content

Instantly share code, notes, and snippets.

@serser
Created December 12, 2018 08:08
Show Gist options
  • Save serser/e5f6d94493a31cf4ecdd57d9ea49d61b to your computer and use it in GitHub Desktop.
Save serser/e5f6d94493a31cf4ecdd57d9ea49d61b to your computer and use it in GitHub Desktop.
change multiple properties on setter with singleton
import functools
def singleton(cls, *args, **kw):
instances = dict()
@functools.wraps(cls)
def _fun():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _fun
@singleton
class A(object):
def __init__(self):
self._fds = False
self.path = 'path/'
@property
def fds(self):
return self._fds
@fds.setter
def fds(self, fds):
self._fds = fds
self.path = '/fds/path' if self._fds else 'path'
print(A().path)
A().fds = True
print(A().path)
class B(object):
_fds = False
def __init__(self):
self.path = '/fds/path' if self._fds else 'path'
print(B().path)
B._fds = True
print(B().path)
@singleton
class C(object):
_fds = False
def __init__(self):
self.path = '/fds/path' if self._fds else 'path'
# print(C().path)
C._fds = True # can be only initialized once
print(C().path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment