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

เขียน Empty Function ใน Python ด้วย pass Statement

ใน Python ไม่สามารถเว้นบล็อคโค้ดว่างได้ (IndentationError) ต้องใช้คำสั่ง pass ซึ่งเป็น no-op (ไม่ทำอะไร) เพื่อเป็น placeholder

Empty Function

# Python
def empty_func():
    pass

# C/C++/Java
void func() { }

Empty Loop

condition = True
while condition:
    pass  # รอ condition เปลี่ยน (เช่น wait for signal)

Empty Conditional

condition = True
if condition:
    pass  # ไม่ทำอะไร
else:
    print("Error")

Use Cases จริง

  • Stub functions ระหว่างพัฒนา (Implement ภายหลัง)
  • Abstract base classes ที่บังคับให้ subclass implement
  • Exception handling ที่ต้องการ ignore error
  • Loop/conditional ที่ logic ยังไม่เขียน
try:
    risky_operation()
except SomeError:
    pass  # เงียบๆ ไม่ log, ไม่ re-raise

คำเตือน

ใช้ pass ให้มีเหตุผล อย่าทิ้งไว้จนลืม implement จริง ควรมี TODO comment:

def calculate_tax(income):
    # TODO: Implement tax brackets
    pass