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

การดึงชื่อฟังก์ชัน (Function Name) ใน Python

การได้ชื่อฟังก์ชันขณะรันไทม์ (Runtime) ทำได้ต่างกันใน Python 2 และ Python 3

Python 2 (Deprecated)

ใช้ attribute func_name

def testing_function():
    """This is a simple function for testing"""
    return None

print("Function name is (Python2) '{}'".format(testing_function.func_name))
Function name is (Python2) 'testing_function'

Python 3 (Current Standard)

ใช้ attribute __name__ (dunder name)

def testing_function():
    """This is a simple function for testing"""
    return None

print(f"Function name is (Python3) '{testing_function.__name__}'")
Function name is (Python3) 'testing_function'

การประยุกต์ใช้: Decorator และ Logging

ใช้ __name__ ใน Decorator เพื่อ logging หรือ debugging

import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@logger
def greet(name):
    return f"Hello, {name}!"

greet("World")  # Output: Calling function: greet

หมายเหตุ: functools.wraps ช่วยรักษา __name__, __doc__ และ attributes อื่นๆ ของฟังก์ชันต้นฉบับ