Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Singleton(type):
- _instances = {}
- def __call__(cls, *args, **kwargs):
- if cls not in cls._instances:
- cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
- return cls._instances[cls]
- @property
- def instance(cls):
- return cls()
- # Usage
- class Foo(metaclass=Singleton):
- def __init__(self):
- self.foo = 1
- class Bar(metaclass=Singleton):
- def __init__(self):
- self.bar = 2
- print(Foo.instance.foo)
- print(Bar.instance.bar)
- Foo.instance.foo += 10
- Bar.instance.bar += 20
- print(Foo.instance.foo)
- print(Bar.instance.bar)
- Foo().foo += 10
- Bar().bar += 20
- print(Foo().foo)
- print(Bar().bar)
Add Comment
Please, Sign In to add comment