Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
19
Task/Singleton/Python/singleton-1.py
Normal file
19
Task/Singleton/Python/singleton-1.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
>>> class Borg(object):
|
||||
__state = {}
|
||||
def __init__(self):
|
||||
self.__dict__ = self.__state
|
||||
# Any other class names/methods
|
||||
|
||||
|
||||
>>> b1 = Borg()
|
||||
>>> b2 = Borg()
|
||||
>>> b1 is b2
|
||||
False
|
||||
>>> b1.datum = range(5)
|
||||
>>> b1.datum
|
||||
[0, 1, 2, 3, 4]
|
||||
>>> b2.datum
|
||||
[0, 1, 2, 3, 4]
|
||||
>>> b1.datum is b2.datum
|
||||
True
|
||||
>>> # For any datum!
|
||||
29
Task/Singleton/Python/singleton-2.py
Normal file
29
Task/Singleton/Python/singleton-2.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import abc
|
||||
|
||||
class Singleton(object):
|
||||
"""
|
||||
Singleton class implementation
|
||||
"""
|
||||
__metaclass__ = abc.ABCMeta
|
||||
|
||||
state = 1 #class attribute to be used as the singleton's attribute
|
||||
|
||||
@abc.abstractmethod
|
||||
def __init__(self):
|
||||
pass #this prevents instantiation!
|
||||
|
||||
@classmethod
|
||||
def printSelf(cls):
|
||||
print cls.state #prints out the value of the singleton's state
|
||||
|
||||
#demonstration
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
a = Singleton() #instantiation will fail!
|
||||
except TypeError as err:
|
||||
print err
|
||||
Singleton.printSelf()
|
||||
print Singleton.state
|
||||
Singleton.state = 2
|
||||
Singleton.printSelf()
|
||||
print Singleton.state
|
||||
9
Task/Singleton/Python/singleton-3.py
Normal file
9
Task/Singleton/Python/singleton-3.py
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
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]
|
||||
|
||||
class Logger(object):
|
||||
__metaclass__ = Singleton
|
||||
2
Task/Singleton/Python/singleton-4.py
Normal file
2
Task/Singleton/Python/singleton-4.py
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
class Logger(metaclass=Singleton):
|
||||
pass
|
||||
Loading…
Add table
Add a link
Reference in a new issue