Skip to content

Polymorphism 多态 of a class in Python

Polymorphism means multiple state. It means that a same action that is done but different object will get different state / results.

Example of polymorphism

  • Animal (Dog / Cat) -> Speak -> Sound ("Bark" / "Meow")
  • Class: Object -> Behaviour -> Results

Example of polymorphism

Example

polymorphism-class.py

py
# Class
# Parent class
class Animal:
    
    def speak(self):
        pass
        
# Children class
class Dog(Animal):
    
    def speak(self):
        print("Bark !")
        
class Cat(Animal):
    
    def speak(self):
        print("Meow !")
        
class UnkownAnimals(Animal):
   
    def speak(self):
        print("...")
        
# Object
dog = Dog()
cat = Cat()
new_species = UnkownAnimals()
        
# Action
def speaking(animal: Animal):
    animal.speak()
    
# Results
speaking(dog)
speaking(cat)
speaking(new_species)

Output:

Bark !
Meow !
...

Abstract Class

Defines the "what" (a blueprint or contract) but doesn't provide the full implementation. Abstract class

  • Example
py
def speak(self):
    pass
  • With the keyword pass mean we define a behaviour but doesn't provide the full implementation. But the behaviour will be implement on a Children class.

Why we using abstract class

Why using abstract classWhy using abstract class

Example

abstract-class.py

py
class PaymentMethod:
    
    def pay(self):
        pass
    
class CardPay(PaymentMethod):
    
    def pay(self):
        print("Using card to pay")
        
class AppPay(PaymentMethod):
    
    def pay(self):
        print("Using Money APP to pay")
        
class CashPay(PaymentMethod):
    
    def pay(self):
        print("Using cash to pay")
        
card = CardPay()
cash = CashPay()
app = AppPay()

def PayBill(payment_method: PaymentMethod):
    payment_method.pay()
    
PayBill(cash)
PayBill(card)
PayBill(app)

Output:

Using cash to pay
Using card to pay
Using Money APP to pay

Conclusion

Conclusion