Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python รองรับ Polymorphism หรือไม่?

ใช่ Python รองรับ Polymorphism (พหุรูป)

คำว่า Polymorphism หมายถึง "มีหลายรูปแบบ"

Polymorphism เป็นคุณสมบัติสำคัญของการกำหนด Class ใน Python ที่ใช้เมื่อคุณมีเมธอดที่ชื่อเหมือนกันข้าม Class หรือ Subclass

Polymorphism สามารถทำได้ผ่าน Inheritance โดย Subclass ใช้เมธอดของ Base Class หรือ Override (เขียนทับ) มัน

สองประเภทของ Polymorphism

  • Overloading (การโอเวอร์โหลด)
  • Overriding (การโอเวอร์ไรด์)

Overloading

เกิดขึ้นเมื่อมีเมธอดสองตัวขึ้นไปใน Class เดียวกัน มีชื่อเมธอดเหมือนกันแต่พารามิเตอร์ต่างกัน

Overriding

หมายถึงมีเมธอดสองตัวที่มีชื่อและพารามิเตอร์เหมือนกัน (Method Signature เหมือนกัน) ตัวหนึ่งอยู่ใน Parent Class อีกตัวใน Child Class

ตัวอย่าง Overriding

class Fish:
    def swim(self):
        print("The Fish is swimming.")
    
    def swim_backwards(self):
        print("The Fish can swim backwards, but can sink backwards.")
    
    def skeleton(self):
        print("The fish's skeleton is made of cartilage.")

class Clownfish:
    def swim(self):
        print("The clownfish is swimming.")
    
    def swim_backwards(self):
        print("The clownfish can swim backwards.")
    
    def skeleton(self):
        print("The clownfish's skeleton is made of bone.")

a = Fish()
a.skeleton()

b = Clownfish()
b.skeleton()

ผลลัพธ์

The fish's skeleton is made of cartilage.
The clownfish's skeleton is made of bone.

ทั้งสอง Class มีเมธอด skeleton() ชื่อเดียวกัน แต่การทำงานต่างกัน (Overriding) เมื่อเรียกเมธอดเดียวกันบนออบเจกต์ที่ต่างกัน จะได้พฤติกรรมที่ต่างกันตาม Class ของออบเจกต์นั้น