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

วิธี Override เมธอดคลาสใน Python

Overriding คือคุณสมบัติของคลาสในการเปลี่ยน Implementation ของเมธอดที่ Base Class มอบให้

Overriding สำคัญมากใน OOP ทำให้ Inheritance ใช้พลังเต็มที่ ด้วย Method Overriding คลาสอาจ "คัดลอก" คลาสอื่น หลีกเลี่ยงโค้ดซ้ำ และปรับปรุง/ปรับแต่งบางส่วน Method Overriding จึงเป็นส่วนหนึ่งของกลไก Inheritance

ใน Python Method Overriding เกิดขึ้นโดยการนิยามเมธอดใน Child Class ที่มีชื่อเดียวกับเมธอดใน Parent Class เมื่อนิยามเมธอดในออบเจ็กต์ มันจะตอบสนอง Method Call นั้น Implementation ของ Ancestor จึงไม่เข้ามามีส่วน

class Parent(object):
    def __init__(self):
        self.value = 4
    def get_value(self):
        return self.value

class Child(Parent):
    def get_value(self):
        return self.value + 1

ตอนนี้ Child Objects พฤติกรรมต่างออกไป:

>>> c = Child()
>>> c.get_value()
5