Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Implementation of Singleton pattern
#decorator, modyfies new_cls def _singleton(new_cls): instance = new_cls() #2 def new(cls): if isinstance(instance, cls): #5 return instance else: raise TypeError("I can only return instance of {}, caller wanted {}".format(new_cls, cls)) new_cls.__new__ = new #3 new_cls.__init__ = lambda self: None #4 return new_cls #decorator, creates new class def singleton(cls): new_cls = type('singleton({})'.format(cls.__name__), (cls,), {} ) #1 return _singleton(new_cls) #metaclass def meta_singleton(name, bases, attrs): new_cls = type(name, bases, attrs) #1 return _singleton(new_cls) #tests if __name__=='__main__': def val(expr): print('{}: {}'.format(expr, eval(expr))) class Base: def __init__(self): print("{}'s instance created".format(type(self).__name__)) @singleton class Singleton(Base): pass val('Singleton() is Singleton()') class MetaSingleton(Base, metaclass=meta_singleton): pass val('MetaSingleton() is MetaSingleton()') class Derived(Singleton): pass #Derived() #fails class MetaDerived(Singleton): pass #MetaDerived() #fails
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
snake water gun game
hw11
Remove all Adjacent duplicates using a loop
prog1.py
http://rextester.com/HYVN80193
pattern(T).py
linked_lists
XII-F
ASICC art
Ciklusok
Please log in to post a comment.