Decorators Advanced
Decorator patterns ขั้นสูงสำหรับ real-world applications รวมถึง class decorators และ decorator factories
ทบทวน Decorator พื้นฐาน
Section titled “ทบทวน Decorator พื้นฐาน”import functools
# Decorator คือ function ที่ wrap function อื่นdef simple_decorator(func): @functools.wraps(func) # Preserve metadata def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") result = func(*args, **kwargs) print(f"Finished {func.__name__}") return result return wrapper
@simple_decoratordef greet(name): """Greet someone""" return f"Hello, {name}!"
# @decorator เทียบเท่า: greet = simple_decorator(greet)print(greet("Alice"))print(f"\nFunction name: {greet.__name__}")print(f"Docstring: {greet.__doc__}")เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google