Skip to content
เข้าสู่ระบบ

Decorators เดคอเรเตอร์

Decorators เป็นฟีเจอร์ที่ทรงพลังใน Python ใช้สำหรับแก้ไขหรือเพิ่มความสามารถให้กับ functions และ classes โดยไม่ต้องแก้ไขโค้ดเดิม

ทำความเข้าใจ Decorators

Section titled “ทำความเข้าใจ Decorators”

Decorator คือฟังก์ชันที่รับฟังก์ชันเป็น argument และคืนฟังก์ชันใหม่ที่มีความสามารถเพิ่มเติม

# Decorator เป็นฟังก์ชันที่ wrap ฟังก์ชันอื่น
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
# ใช้ decorator
@my_decorator
def say_hello():
print("Hello!")
# เรียกใช้
say_hello()
# @ syntax เทียบเท่ากับ:
# say_hello = my_decorator(say_hello)

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด