-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
79 lines (57 loc) · 1.69 KB
/
main.py
File metadata and controls
79 lines (57 loc) · 1.69 KB
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
75
76
77
78
79
from __future__ import annotations
import abc
class Alg(abc.ABC):
"""
Abstract implementation of Alg algorithm.
Alg algorithm uses the information from its attached type.
it only attaches to Core class.
"""
def __init__(self):
self.core: Core | None = None
def __get__(self, obj: Core, objtype):
# object type is a class and classes are signleton
# so we can actually check them by `is` keyword.
if objtype is Core:
self.core = obj
return self
else:
raise AttributeError()
def __call__(self):
return self.run()
@abc.abstractmethod
def run(self):
pass
class Alg1(Alg):
"""
First implementation of the Alg algorithm.
"""
def run(self):
if self.core is not None:
return f"Alg-1 from {self.core.name}"
class Alg2(Alg):
"""
Second implementation of the Alg algorithm.
"""
def run(self):
if self.core is not None:
return f"Alg-2 from {self.core.name}"
class Core:
"""
Core uses Alg algorithm and we wnat to control its implementation
of Alg alorithm.
"""
# the descriptor must be in either the owner’s class dictionary
# or in the class dictionary for one of its parents
# by default core uses first implemtnation of Alg.
alg: Alg = Alg1()
def __init__(self, name: str = "default"):
self.name = name
c1 = Core("elahe")
c2 = Core("raha")
assert c1.alg() == "Alg-1 from elahe"
assert c2.alg() == "Alg-1 from raha"
# sadlly this chnages implementation
# on all instances.
Core.alg = Alg2()
assert c1.alg() == "Alg-2 from elahe"
assert c2.alg() == "Alg-2 from raha"