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

บทนำ Classes และ Inheritance ใน Python

Object-Oriented Programming สร้างรูปแบบโค้ดที่นำกลับมาใช้ซ้ำได้ เพื่อป้องกัน Code Redundancy วิธีหนึ่งคือ Inheritance (การสืบทอด) เมื่อ Subclass ใช้โค้ดจาก Base Class

Inheritance คือเมื่อคลาสหนึ่งใช้โค้ดที่เขียนในอีกคลาสหนึ่ง

Child Classes หรือ Subclasses สืบทอด Methods และ Variables จาก Parent Classes หรือ Base Classes

เพราะ Child Subclass สืบทอดจาก Parent Base Class Child Class จึงนำโค้ดของ Parent ไปใช้ซ้ำได้ ทำให้นักเขียนโปรแกรมเขียนโค้ดน้อยลงและลด Redundancy

Syntax

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

ตัวอย่าง

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