ปรับแต่ง subclass
การสืบทอด (inheritance) มีประสิทธิภาพมาก เพราะช่วยให้นำโค้ดกลับมาใช้ใหม่และปรับแต่งได้โดยไม่ต้องเขียนใหม่ทั้งหมด การเรียกใช้เมธอดของ parent class ภายใน child class ช่วยให้โค้ดกระชับและดูแลรักษาได้ง่ายขึ้น
ในแบบฝึกหัดนี้ จะทำงานต่อกับคลาส Manager ที่สืบทอดมาจากคลาส Employee โดยจะเพิ่ม constructor ที่ต่อยอดจาก constructor ของ Employee พร้อมรับ argument เพิ่มเติมสำหรับระบุโปรเจกต์ที่ผู้จัดการกำลังดูแลอยู่
ไฟล์ script.py มีเวอร์ชันย่อของคลาส Employee และโครงของคลาส Manager ที่สร้างไว้ก่อนหน้านี้เตรียมไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ
คำแนะนำการฝึกหัด
- เพิ่ม constructor ให้กับ
Managerโดยรับ argument ได้แก่name,salary(ค่าเริ่มต้นเป็น50000) และproject(ค่าเริ่มต้นเป็นNone) - ภายใน constructor ของ
Managerให้เรียก constructor ของคลาสEmployeeพร้อมส่ง argument สามตัวที่กำหนดไว้ใน constructor ของ parent class - ใช้
selfเพื่อกำหนด attribute ที่เกี่ยวข้องให้กับ argumentproject
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
class Employee:
def __init__(self, name, salary=30000):
self.name = name
self.salary = salary
def give_raise(self, amount):
self.salary += amount
class Manager(Employee):
# Add a constructor
def __init__(self, name, ____=____, ____=____):
# Call the parent's constructor
____.____(____, ____, salary)
# Assign project attribute
____.____ = ____
def display(self):
print("Manager ", self.name)