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

Class Inheritance ใน Python ทำงานอย่างไร

Inheritance ในคลาส

แทนที่จะนิยามคลาสใหม่ทั้งหมด สามารถสร้างคลาสโดยสืบทอดจากคลาสที่มีอยู่แล้ว โดยระบุ Parent Class ในวงเล็บหลังชื่อคลาสใหม่

Child Class สืบทอด Attributes ของ Parent Class และใช้ได้เหมือนนิยามใน Child Class เอง Child Class ยัง Override Data Members และ Methods ของ Parent ได้อีกด้วย

Syntax

class SubClassName (ParentClass1[, ParentClass2, ...]):
    'Optional class documentation string'
    class_suite

ตัวอย่าง

#!/usr/bin/python
class Parent:
    parentAttr = 100
    def __init__(self):
        print("Calling parent constructor")
    def parentMethod(self):
        print('Calling parent method')
    def setAttr(self, attr):
        Parent.parentAttr = attr
    def getAttr(self):
        print("Parent attribute :", Parent.parentAttr)

class Child(Parent):
    def __init__(self):
        print("Calling child constructor")
    def childMethod(self):
        print('Calling child method')

c = Child()
c.childMethod()
c.parentMethod()
c.setAttr(200)
c.getAttr()

ผลลัพธ์

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200