Single-line docstrings
Docstring ใช้สำหรับอธิบายวัตถุประสงค์ของฟังก์ชัน แม้ชื่อฟังก์ชันควรสื่อความหมายได้ในตัว แต่ก็ต้องสมดุลกับความยาวของชื่อ docstring จึงช่วยให้เพิ่มรายละเอียดได้มากขึ้น
ในแบบฝึกหัดนี้ จะนำฟังก์ชัน calculate_discount() ที่สร้างไว้ก่อนหน้า มาเพิ่ม single-line docstring
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python ระดับกลางสำหรับนักพัฒนา
คำแนะนำการฝึกหัด
- เพิ่ม docstring ว่า
"""Calculate the discounted price of a product.""" - เข้าถึง docstring ของฟังก์ชันโดยใช้แอตทริบิวต์ที่เหมาะสม
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def calculate_discount(price, discount_percent=15, round_result=True):
# Add a single-line docstring
____
discounted_price = price - (price * (discount_percent / 100))
if round_result == True:
return round(discounted_price, 2)
else:
return discounted_price
# Access the docstring
print(calculate_discount.____)