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

วิธีเช็คว่า Python Variable มีอยู่จริงหรือไม่

ใช้ locals(), globals(), hasattr()

ตัวอย่าง

x = 10

class foo:
    g = 'rt'
    def bar(self):
        m = 6
        print(locals())
        if 'm' in locals():
            print('m is local variable')
        else:
            print('m is not a local variable')

f = foo()
f.bar()

print(globals())
if hasattr(f, 'g'):
    print('g is an attribute')
else:
    print("g is not an attribute")

if 'x' in globals():
    print('x is a global variable')

ผลลัพธ์

{'self': <__main__.foo instance at 0x...>, 'm': 6}
m is local variable
{'f': <__main__.foo instance at 0x...>, '__builtins__': , 'x': 10, 'foo': , ...}
g is an attribute
x is a global variable