Skip to content

Commit a1b511f

Browse files
Polymorphism in Python
1 parent 10a5e0e commit a1b511f

File tree

2 files changed

+107
-0
lines changed

2 files changed

+107
-0
lines changed

lectures-code/polymorphism-1.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Copyright (C) Deepali Srivastava - All Rights Reserved
2+
# This code is part of Python course available on CourseGalaxy.com
3+
4+
class Car:
5+
def start(self):
6+
print('Engine started')
7+
def move(self):
8+
print('Car is running')
9+
def stop(self):
10+
print('Brakes applied')
11+
12+
class Clock:
13+
def move(self):
14+
print('Tick Tick Tick')
15+
def stop(self):
16+
print('Clock needles stopped')
17+
18+
19+
class Person:
20+
def move(self):
21+
print('Person walking')
22+
23+
def stop(self):
24+
print('Taking rest')
25+
26+
def talk(self):
27+
print('Hello')
28+
29+
car = Car()
30+
clock = Clock()
31+
person = Person()
32+
33+
def do_something(x):
34+
x.move()
35+
x.stop()
36+
37+
do_something(car)
38+
do_something(clock)
39+
do_something(person)
40+

lectures-code/polymorphism-2.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright (C) Deepali Srivastava - All Rights Reserved
2+
# This code is part of Python course available on CourseGalaxy.com
3+
4+
class Rectangle:
5+
name = 'Rectangle'
6+
def __init__(self, length, breadth):
7+
self.length = length
8+
self.breadth = breadth
9+
10+
def area(self):
11+
return self.length * self.breadth
12+
13+
def perimeter(self):
14+
return 2 * (self.length + self.breadth)
15+
16+
class Triangle:
17+
name = 'Triangle'
18+
def __init__(self, s1, s2, s3):
19+
self.s1 = s1
20+
self.s2 = s2
21+
self.s3 = s3
22+
23+
def area(self):
24+
sp = (self.s1 + self.s2 + self.s3) / 2
25+
return ( sp*(sp-self.s1)*(sp-self.s2)*(sp-self.s3) ) ** 0.5
26+
27+
def perimeter(self):
28+
return self.s1 + self.s2 + self.s3
29+
30+
class Circle:
31+
name = 'Circle'
32+
def __init__(self, radius):
33+
self.radius = radius
34+
35+
def area(self):
36+
return 3.14 * self.radius * self.radius
37+
38+
def perimeter(self):
39+
return 2 * 3.14 * self.radius
40+
41+
r1 = Rectangle(13,25)
42+
r2 = Rectangle(14,16)
43+
t1 = Triangle(14,17,12)
44+
t2 = Triangle(25,33,52)
45+
c1 = Circle(14)
46+
c2 = Circle(25)
47+
48+
def find_area_perimeter(shape):
49+
print(shape.name)
50+
print('Area : ', shape.area() )
51+
print('Perimeter : ', shape.perimeter() )
52+
53+
find_area_perimeter(t2)
54+
find_area_perimeter(c1)
55+
find_area_perimeter(r2)
56+
57+
shapes = [r1,r2,t1,t2,c1,c2]
58+
59+
total_area = 0
60+
total_perimeter = 0
61+
62+
for shape in shapes:
63+
total_area += shape.area()
64+
total_perimeter += shape.perimeter()
65+
66+
print(total_area, total_perimeter)
67+

0 commit comments

Comments
 (0)