Popular Posts

Monday, September 14, 2020

Python Beginner: Class inheritance

 Hello, Developer! 😄


Today, we will learn the "Inheritance". The "Inheritance" function allows you to use other class functions without codes copy. If you inherit other classes' properties, you can improve programming productivity through this function.


Class Inheritance Form

class Sample_class_name(Inheritance parent class): 

    def additional_property # You can add additional properties on parents' all properties

    def override_property # If you want to override parent properties, you can redefine property with the same property name


I showed all exercise codes and execution result as following.

Chef.py

class Chef:

def make_chicken(self):
print("The chef makdes a chicken.")

def make_salad(self):
print("The chef makes a salad.")

def make_special_dish(self):
print("The chef makes bbq ribs.")

ChineseChef.py

class ChineseChef: # ChineseChef can do everything which Chef can do

def make_chicken(self):
print("The chef makdes a chicken.")

def make_salad(self):
print("The chef makes a salad.")

def make_special_dish(self):
print("The chef makes soup noodle.")

def make_fried_rice(self):
print("The chef makes fried rice.")

InheritanceChineseChef.py

from Chef import Chef

class IchineseChef(Chef):

def make_special_dish(self):
print("The Chef makes a orange chicken.")


def make_fried_rice(self):
print("The Chef makes a fried rice.")

Inheritance.py

from Chef import Chef
from ChineseChef import ChineseChef
from InheritanceChineseChef import IchineseChef

myChef = Chef()
myChef.make_special_dish()

myChineseChef = ChineseChef()
myChineseChef.make_special_dish()

ImyChineseChef = IchineseChef()
ImyChineseChef.make_fried_rice()

Execution Result

Can you see the same result on your PC? Congratulations! Now you can utilize class inheritance function in the Python.


Alright, let's see in the next post, Python developer! 😊

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...