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

วิธีหาจำนวนอาร์กิวเมนต์ของฟังก์ชัน Python

ใช้โมดูล inspect ฟังก์ชัน inspect.getargspec() คืนค่า ArgSpec object

ตัวอย่าง

# qux.py
def aMethod1(arg1, arg2): pass
def aMethod2(arg1, arg2, arg3, arg4, arg5): pass

# fubar.py
import qux
import inspect

x = inspect.getargspec(qux.aMethod1)
y = inspect.getargspec(qux.aMethod2)
print(len(y[0]))  # 5

getargspec(func)[0] คือ list ของชื่อพารามิเตอร์ปกติ len() ให้จำนวน

หมายเหตุ: Python 3.5+ ควรใช้ inspect.signature() แทน