Constructor ทางเลือก
Python ยังรองรับการนิยาม เมธอด ระดับคลาส โดยใช้ decorator @classmethod และอาร์กิวเมนต์พิเศษตัวแรกชื่อ cls การใช้งานหลักของ class method คือการนิยามเมธอดที่คืนค่าเป็น instance ของคลาส โดยไม่จำเป็นต้องใช้โค้ดเดียวกับ __init__()
ตัวอย่างเช่น สมมติว่ากำลังพัฒนาแพ็กเกจสำหรับข้อมูลอนุกรมเวลา และต้องการสร้างคลาสของตัวเองสำหรับจัดการวันที่ชื่อ BetterDate โดยมี attribute ได้แก่ year, month และ day นอกจาก constructor ที่รับค่าปี เดือน และวันโดยตรงแล้ว ยังต้องการสร้าง BetterDate object จาก string เช่น 2020-04-30 ได้ด้วย
ฟังก์ชันต่อไปนี้อาจเป็นประโยชน์:
- เมธอด
.split("-")จะแบ่ง string ที่ตำแหน่ง"-"ออกเป็น array เช่น"2020-04-30".split("-")จะคืนค่า["2020", "04", "30"] int()จะแปลง string ให้เป็นตัวเลข เช่นint("2019")จะได้2019
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเขียนโปรแกรมเชิงวัตถุใน Python
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
class BetterDate:
# Constructor
def __init__(self, year, month, day):
# Recall that Python allows multiple variable assignments in one line
self.year, self.month, self.day = year, month, day
# Define a class method from_str
____
def from_str(____, datestr):
# Split the string at "-" and convert each part to integer
parts = datestr.split("-")
year, month, day = int(parts[0]), ____, ____
# Return the class instance
____ ____(____, ____, ____)
bd = BetterDate.from_str('2020-04-30')
print(bd.year)
print(bd.month)
print(bd.day)