Skip to content

Commit f1c34ff

Browse files
committed
super funtion
1 parent bb360b8 commit f1c34ff

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Super()
2+
# Using super() in Python has several advantages over using the parent class
3+
# name:
4+
# 1. "super()" make your code maintainable, which means if you decide to change
5+
# the parent class name or the inheritance hierarchy, by using super() there is
6+
# there is no need to change the class name in all the subclasses (children
7+
# classes).
8+
# 2. Using "super()" in multi-level inheritance is convenient if you understand
9+
# the MRO of your classes.
10+
11+
# Let's take an example, showing the result if the classes have inside them a
12+
# method with the same name:
13+
14+
class Parent:
15+
16+
def who_I_am(self):
17+
return "I am the Parent"
18+
19+
20+
class Child1(Parent):
21+
22+
def who_I_am(self):
23+
print(f"{super().who_I_am()}, inside Child1")
24+
return "I am Child1"
25+
26+
27+
class Child2(Parent):
28+
29+
def who_I_am(self):
30+
print(f"{super().who_I_am()}, inside Child2")
31+
return "I am Child2"
32+
33+
34+
class GrandChild(Child1, Child2):
35+
36+
def who_I_am(self):
37+
print(f"{super().who_I_am()}, inside GrandChild")
38+
return "I am the GrandChild"
39+
40+
41+
# print(GrandChild.mro())
42+
43+
grand_child = GrandChild()
44+
# print(grand_child.who_I_am())
45+
46+
47+
# Let's take an example with different methods names for "Child2" class and
48+
# "GrandChild" class:
49+
class Parent:
50+
51+
def who_I_am(self):
52+
return "I am the Parent"
53+
54+
55+
class Child1(Parent):
56+
57+
def who_I_am_one(self):
58+
print(f"{super().who_I_am()}, inside Child1")
59+
return "I am Child1"
60+
61+
62+
class Child2(Parent):
63+
64+
def who_I_am_two(self):
65+
print(f"{super().who_I_am()}, inside Child2")
66+
return "I am Child2"
67+
68+
69+
class GrandChild(Child1, Child2):
70+
71+
def who_I_am_three(self):
72+
print(f"{super().who_I_am_one()}, inside GrandChild")
73+
return "I am the GrandChild"
74+
75+
76+
# print(GrandChild.mro())
77+
78+
grand_child = GrandChild()
79+
# print(grand_child.who_I_am_three())
80+
81+
82+
# "super()" is a powerful tool if it is used correctly and carefully, but be
83+
# carful when using it in mutli-level inheritance, because it may complicate
84+
# your code and you may get undesirable results.

0 commit comments

Comments
 (0)