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

วิธีนิยามฟังก์ชัน Python ในขณะรัน (Runtime)

ใช้โมดูล types และ types.FunctionType() สร้างฟังก์ชันจาก bytecode ที่ compile จากสตริง

ตัวอย่างที่ Python prompt

>>> import types
>>> dynf = types.FunctionType(compile('print "Really Works"', 'dyn.py', 'exec'), {})
>>> dynf()
Really Works

วิธีนี้ใช้สร้างฟังก์ชันแบบไดนามิกขณะรันโปรแกรม