Python Class Polymorphism with Songs

python day 27

Recently there are so many Singing TV shows, The Big Band, Super Band, Sisters in Winds and Waves, Rap of China.  So today let’s make a Python Abstract Class that is able to pass to subclasses and print out song lyrics about cute animals.
Why do we choose these songs?
Because it’s my program so i can print out the songs I like!
If you have different choices, It is a great time to start making your own program!

Key Point:

ABCs, ABCMeta, abstractmethod 

The module grant us to contsruct an Abstract Bases Class, which only declare, but contains NO implementation.
It requires subclasses to provide implementations for the abstract methods.

Python Code:

from abc import ABCMeta, abstractmethod

class pet(object, metaclass=ABCMeta):
    def __init__(self, nickname):
        self._nickname= nickname
        
    @abstractmethod
    def song(self):
        pass

class snail(pet):
    def song(self):
        print("a little %s is going up step by step! \n小小 %s 要一步一步往上爬! \n" %(self._nickname,self._nickname ), end="\n")
        
class kitty(pet):
    def song(self):
        print("Let's be %s meow meow meow, make a little naughty sound \n我们一起学 %s 叫,一起喵喵喵喵... \n" %(self._nickname,self._nickname), end="\n")
                
class dragon(pet):
    def song(self):
        print("There's a %s in the far east, his name is China \n遥远的东方有一条 %s,他的名字叫中国 \n" %(self._nickname,self._nickname), end="\n")

class horse(pet):
    def song(self):
        print("You are like a wild %s , but i dont have a land of grass. \n你是一匹野 %s, 可惜我家里没有草原 \n" %(self._nickname,self._nickname), end="\n")

Make a Def  to call the class 

def pet_song():
    pets=[snail("snail"), kitty("kitty"), dragon("dragon"), horse("horse")]
    for pet in pets:
        pet.song()

pet_song()

Output:

a little snail is going up step by step! 
小小 snail 要一步一步往上爬! 

Let's be kitty meow meow meow, make a little naughty sound 
我们一起学 kitty 叫,一起喵喵喵喵... 

There's a dragon in the far east, his name is China 
遥远的东方有一条 dragon,他的名字叫中国 

You are like a wild horse , but i dont have a land of grass. 
你是一匹野 horse, 可惜我家里没有草原

Happy Studying and Have fun singing!!

 

Ref:

https://github.com/jackfrued/Python-100-Days/blob/master/Day01-15/09.%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%BF%9B%E9%98%B6.md

 

https://www.python-course.eu/python3_abstract_classes.php

歌曲:

蜗牛-周杰伦 jay chou

一起学猫叫 – 小峰峰

龙的传人 -王力宏 leehom wang

董小姐- 宋东野

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social media & sharing icons powered by UltimatelySocial
%d bloggers like this: