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

นับตัวแปร Local ในฟังก์ชัน Python

Python เก็บข้อมูล Local Variables ของฟังก์ชันไว้ใน __code__.co_nlocals

ตัวอย่าง

def scope():
    a = 25.5
    b = 5
    str_ = 'Tutorialspoint'

print("Number of local variables:", scope.__code__.co_nlocals)
# Output: 3

ตัวอย่างเพิ่มเติม

def empty():
    pass

def scope():
    a, b, c = 9, 23.4, True
    str_ = 'Tutorialspoint'

print("empty():", empty.__code__.co_nlocals)    # 0
print("scope():", scope.__code__.co_nlocals)    # 4

ผลลัพธ์

empty(): 0
scope(): 4

รายละเอียด __code__ Object

def example(x, y, z=10):
    a = 1
    b = 2
    return a + b

code = example.__code__
print("co_nlocals:", code.co_nlocals)      # 5 (x, y, z, a, b)
print("co_argcount:", code.co_argcount)    # 3 (x, y, z)
print("co_varnames:", code.co_varnames)    # ('x', 'y', 'z', 'a', 'b')

ประโยชน์: Debugging, Code Analysis, Metaprogramming