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

อธิบาย Inheritance vs Instantiation สำหรับ Python Classes

Inheritance (การสืบทอด)

Python เป็น Object-Oriented Language รองรับ Inheritance รวมถึง Multiple Inheritance Classes สามารถสืบทอดจาก Classes อื่นๆ ได้ Class สามารถสืบทอด Attributes และ Behavior Methods จากอีก Class หนึ่ง เรียกว่า Superclass Class ที่สืบทอดจาก Superclass เรียกว่า Subclass หรือ Heir Class หรือ Child Class อีกนัยหนึ่ง Inheritance หมายถึงการ Define Class ใหม่ด้วยการปรับเปลี่ยนน้อยหรือไม่มีเลยจาก Class ที่มีอยู่แล้ว

class A:
    # define your class A
    pass

class B:
    # define your class B
    pass

class C(A, B):
    # subclass of A and B
    pass

Instantiation (การสร้าง Instance)

Instantiating a Class คือการสร้าง Copy ของ Class ซึ่งสืบทอด Class Variables และ Methods ทั้งหมด Instantiating a Class ใน Python ง่ายมาก เพื่อ Instantiate Class เราเพียงแค่เรียก Class เหมือน Function ส่ง Arguments ที่ Method __init__ กำหนด Return Value จะเป็น Object ที่สร้างใหม่

ตัวอย่าง

class Foo():
    def __init__(self, x, y):
        print(x + y)

f = Foo(3, 4)

Output

7