-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpolymorphism.py
More file actions
108 lines (72 loc) · 1.69 KB
/
polymorphism.py
File metadata and controls
108 lines (72 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class Hewan:
def __init__(self, nama):
self.nama = nama
def suara(self):
print(f"{self.nama} bersuara")
class Anjing(Hewan):
def suara(self):
print(f"{self.nama} guk guk")
class Kucing(Hewan):
def suara(self):
print(f"{self.nama} meow")
class Sapi(Hewan):
def suara(self):
print(f"{self.nama} moooo")
hewan_list = [
Anjing("Anjing"),
Kucing("Kucing"),
Sapi("Sapi")
]
for hewan in hewan_list:
hewan.suara()
class Mobil:
def start(self):
print("Mobil berjalan")
class Motor:
def start(self):
print("Motor berjalan")
class Perahu:
def start(self):
print("Perahu berjalan")
def operasikan_kendaraan(kendaraan):
kendaraan.start()
kendaraan_list = [
Mobil(),
Motor(),
Perahu()
]
for kendaraan in kendaraan_list:
operasikan_kendaraan(kendaraan)
class Apple:
def __init__(self, jumlah):
self.jumlah = jumlah
def __add__(self, other):
return Apple(self.jumlah + other.jumlah)
def __str__(self):
return f"Apple {self.jumlah}"
apple1 = Apple(10)
apple2 = Apple(20)
apple3 = apple1 + apple2
print(apple3)
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
shape_list = [
Rectangle(10, 20),
Circle(10)
]
for shape in shape_list:
print(shape.area())