-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisitor2.py
78 lines (52 loc) · 1.62 KB
/
visitor2.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
75
76
from abc import ABC, abstractmethod
class IVisitor(ABC):
@abstractmethod
def visit(self):
raise NotImplementedError('Method must be implemented by subclass')
class IVisitable(ABC):
@abstractmethod
def accept(self):
raise NotImplementedError('Method must be implemented by subclass')
class Body(IVisitable):
def __init__(self, name, price):
self.name = name
self.price = price
def accept(self, visitor):
return visitor.visit(self)
class Engine(IVisitable):
def __init__(self, name, price):
self.name = name
self.price = price
def accept(self, visitor):
return visitor.visit(self)
class Wheel(IVisitable):
def __init__(self, name, price):
self.name = name
self.price = price
def accept(self, visitor):
return visitor.visit(self)
class Car(IVisitable):
def __init__(self, name):
self.name = name
self._parts = [
Body("Utility", 1001),
Engine("V8 engine", 2555),
Wheel("FrontLeft", 136),
Wheel("FrontRight", 136),
Wheel("BackLeft", 152),
Wheel("BackRight", 152),
]
def accept(self, visitor):
for part in self._parts:
part.accept(visitor)
return visitor.visit(self)
class TotalPriceVisitor(IVisitor):
total_price = 0
@classmethod
def visit(cls, element):
if hasattr(element, 'price'):
cls.total_price += element.price
return cls.total_price
car = Car('pride')
car.accept(TotalPriceVisitor)
print('totla ', TotalPriceVisitor.total_price)