ในบทช่วยสอนนี้ เราจะดูแนวทางปฏิบัติที่ดี (best practices) สำหรับการจัดโครงสร้างโปรแกรม Python มาดูทีละข้อ
ใช้ Tab สำหรับการย่อหน้า (Indentation)
การใช้ Tab สำหรับ indentation ทำให้โค้ดอ่านง่ายกว่าการใช้ space สลับกันสำหรับฟังก์ชันและเมธอดหลายๆ ตัว คุณสามารถตั้งจำนวน space ต่อ Tab ในการตั้งค่า code editor ได้
ตัวอย่าง
# ตัวอย่าง
def sample(random):
# statement 1
# statement 2
# ...
return random
อย่าเขียนเกิน 79 ตัวอักษรต่อบรรทัด
Python ไม่แนะนำให้เขียนเกิน 79 ตัวอักษรต่อบรรทัด หลีกเลี่ยงโดยการขึ้นบรรทัดใหม่ด้วย escape character (\) ดูตัวอย่าง
ตัวอย่าง
# ตัวอย่าง
def evaluate(a, b, c, d):
return (2 ** (a + b) / (c // d) ** d + a - d * b) \
- (3 ** (a + b) / (c // d) ** d + a - d * b)
ถ้าต้องตรวจสอบเงื่อนไขหลายอย่างใน if statement อาจเกิน 79 ตัวอักษร ใช้วิธีใดวิธีหนึ่งด้านล่าง
ตัวอย่าง
if (
a + b > c + d and
c + d > e + f and
f + g > a + b
):
print('Hello')
if a + b > c + d and \
c + d > e + f and \
f + g > a + b:
print('Hello')
ใช้ Docstrings
ใช้ docstring ในฟังก์ชันและคลาส ใช้ triple quotes สำหรับ docstrings ตัวอย่างด้านล่าง
ตัวอย่าง
def sample():
\"\"\"This is a function\"\"\"
\"\"\"
This
is
a function
\"\"\"
class Smaple:
\"\"\"This is a class\"\"\"
\"\"\"
This
is
a class
\"\"\"
สรุป
ใช้ Tab indent, จำกัด 79 chars/บรรทัด, เขียน docstring หากมีข้อสงสัย กรุณาแจ้งในส่วนความคิดเห็น