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

เรียกฟังก์ชันของโมดูลจากชื่อเป็น String (getattr)

ใน Python ทุกอย่างคือ Object ฟังก์ชันก็เป็น Attribute ของ Module ใช้ getattr() ดึงมาเรียก

รูปแบบพื้นฐาน

>>> import foo
>>> method_to_call = getattr(foo, 'bar')
>>> result = method_to_call()

กรณีฟังก์ชันอยู่ใน Global/Local Namespace

>>> result = globals()["myfunction"]()
>>> result = locals()["myfunction"]()

ตัวอย่างประยุกต์: Dispatcher Pattern

def handle_json(data): ...
def handle_xml(data): ...
def handle_csv(data): ...

handlers = {
    'json': handle_json,
    'xml': handle_xml,
    'csv': handle_csv,
}

format_type = 'json'  # มาจาก Config/User Input
handler = handlers.get(format_type)
if handler:
    handler(data)
ปลอดภัย: ตรวจสอบชื่อฟังก์ชันก่อน Call (Whitelist) ป้องกัน Arbitrary Code Execution