-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathmain.py
74 lines (52 loc) · 1.43 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(
*args, **kwargs
)
return cls._instances[cls]
class Logger(metaclass=MetaSingleton):
def __init__(self, x):
self.x = x
class Singleton1:
__instance = None
def __new__(cls, nome):
if Singleton1.__instance is None:
Singleton1.__instance = object.__new__(cls)
Singleton1.__instance.__nome = nome
return Singleton1.__instance
@property
def nome(self):
return self.__nome
class Singleton2:
def __new__(cls, nome):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton2, cls).__new__(cls)
cls.instance.__nome = nome
return cls.instance
@property
def nome(self):
return self.__nome
if __name__ == '__main__':
foo = Singleton1('Maria')
print(foo.nome)
print(foo)
bar = Singleton1('Joao')
print(bar.nome)
print(bar)
print(foo is bar)
foo = Singleton2('Maria')
print(foo.nome)
print(foo)
bar = Singleton2('Joao')
print(bar.nome)
print(bar)
print(foo is bar)
# Example using metaclass
logger1 = Logger(1)
logger2 = Logger(2)
print(logger1)
print(logger1.x)
print(logger2)
print(logger2.x)