Popular Posts

Sunday, February 19, 2023

Python Class Inheritance exercise part 2

Hello Python developer!

Today, we will look into class 'inheritance' with my test codes. Because I want to understand about 'class inheritance'.

Let's see following codes and type in Python IDE for execution!

Source codes(Multi_Inheritance.py)

Github link : https://github.com/Cevastian/Python-Developer-start-today/blob/master/Multi_Inheritance.py

class Lion():
color = "yellow"
classification = "animal"

def hunting(self):
print("Lion is hunting")

def attack_claw(self):
print("Claw attack")

class Eagle():
color = "brown"
classification = "bird"

def hunting(self):
print("Eagle is hunting")

def attack_beak(self):
print("Beak attack")

class Shark():
color = "blue"
classification = "fish"

def hunting(self):
print("Shark is hunting")

def attack_teeth(self):
print("Teeth attack")

class Monster(Lion, Eagle, Shark):
color = "green"
classification ="beast"

def playing(self):
print("Monster is playing")

def attack_tail(self):
print("Tail attack")

monster = Monster() # Class instance generating
monster.playing() # monster instance playing method calling
monster.hunting() # monster instance 'Lion' class 'hunting' method by inheritance
monster.attack_teeth() # monster instance 'Shark' class 'attack_teeth' method by inheritance

Executed result

'Monster' class inherited from 'Lion', 'Eagle' and 'Shark' classes. It also has its own method ' playing' and 'attack_tail'. As you know, child class can use parent classes' attributes and methods. Python meet calling of class method, it tried to search in its own class and it fails to search it, Python tried to search it out in the first parent classes' attributes and methods. It still fails to find out the called attributes and method from the first class, Python tried to search it in second parent class.

So, 'monster.hunting' method execution result was 'Lion' classes' method excution result. Because there is no 'hunting' method in 'Monster' class so Python search 'hunting' method from the parent classes by 'Lion', 'Eagle' and 'Shark' sequence by Monster(Lion, Eagle, Shark) class inheritance.

Developer, did you understand 'class inheritance' with above example?

Hope you're fine today with Python codes!

No comments:

Post a Comment

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...