Skip to content

Commit 125ec4e

Browse files
author
raulG91
committed
#27 -python
1 parent 55e3908 commit 125ec4e

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
2+
from abc import ABC, abstractmethod
3+
#Bad example: Open for mofification but not closed
4+
class Character:
5+
def __init__(self,type):
6+
self.type = type
7+
def attack(self):
8+
if self.type == "Fire":
9+
print("Fire attack")
10+
elif self.type == "Water":
11+
print("Water attack")
12+
elif self.type == "Electricity":
13+
print("Electrical attack")
14+
15+
#Correct example
16+
17+
class Character2(ABC):
18+
def __init__(self,type):
19+
self.type = type
20+
@abstractmethod
21+
def attack(self):
22+
pass
23+
24+
class FireCharacter(Character2):
25+
def attack(self):
26+
print("Fire attack")
27+
28+
class WaterCharacter(Character2):
29+
def attack(self):
30+
print("Water attack")
31+
32+
class ElectricityCharacter(Character2):
33+
def attack(self):
34+
print("Electrical attack")
35+
36+
#Extra
37+
38+
class Operation(ABC):
39+
@abstractmethod
40+
def operate(self,a,b):
41+
pass
42+
43+
class Sum(Operation):
44+
def operate(self, a, b):
45+
return a +b
46+
class Diff(Operation):
47+
def operate(self, a, b):
48+
return a - b
49+
class Multiply(Operation):
50+
def operate(self, a, b):
51+
return a*b
52+
class Division(Operation):
53+
def operate(self, a, b):
54+
if not b==0:
55+
return a/b
56+
57+
class Calculator:
58+
def __init__(self) -> None:
59+
self.operations = []
60+
61+
def add_operation(self,name,op):
62+
self.operations.append((name,op))
63+
def operate(self,operation,a,b):
64+
element = list(filter(lambda x: x[0]==operation,self.operations))
65+
if element:
66+
return element[0][1].operate(a,b)
67+
calc = Calculator()
68+
calc.add_operation("Sum",Sum())
69+
calc.add_operation("Diff",Diff())
70+
calc.add_operation("Multiply",Multiply())
71+
calc.add_operation("Division",Division())
72+
print("Sum",calc.operate("Sum",3,5))
73+
print("Diff",calc.operate("Diff",4,3))
74+
print("Multiply",calc.operate("Multiply",4,3))
75+
print("Division",calc.operate("Division",4,2))
76+
77+
class Pow(Operation):
78+
def operate(self, a, b):
79+
return a**b
80+
81+
calc.add_operation("Pow",Pow())
82+
print("Pow",calc.operate("Pow",2,2))

0 commit comments

Comments
 (0)