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

ตัวแปรคลาสทำงานอย่างไรใน Multiple Inheritance ของ Python

ใน Python คลาสสามารถสืบทอดมาจาก Base Class หลายคลาสได้ เรียกว่า Multiple Inheritance

ใน Multiple Inheritance คุณสมบัติของ Base Class ทั้งหมดจะถูกสืบทอดไปยัง Derived Class ไวยากรณ์คล้าย Single Inheritance

class Super1:
    pass

class Super2:
    pass

class MultiDerived(Super1, Super2):
    pass

ในสถานการณ์ Multiple Inheritance แอตทริบิวต์ที่ระบุจะถูกค้นหาในคลาสปัจจุบันก่อน หากไม่พบ จะค้นหาต่อใน Parent Class แบบ Depth-First, Left-to-Right โดยไม่ค้นหาคลาสเดิมซ้ำ

ตัวอย่าง MultiDerived ลำดับค้นหาคือ [MultiDerived, Super1, Super2, object] เรียกว่า Linearization กฎที่ใช้หาลำดับนี้เรียกว่า Method Resolution Order (MRO)

MRO รับประกันว่าคลาสจะปรากฎก่อน Parent ของมัน และกรณีหลาย Parent ลำดับจะเหมือน Tuple ของ Base Classes

ดู MRO ได้จาก __mro__ (คืน Tuple) หรือ mro() (คืน List)

>>> MultiDerived.mro()
[<class '__main__.MultiDerived'>, <class '__main__.Super1'>, <class '__main__.Super2'>, <class 'object'>]