在python中设置静态变量

Python函数的静态变量

C语言中,在函数内部可以定义static类型的变量,这个变量是属于这个函数的全局对象。在Python中也可以实现这样的机制。

def f():
    if not hasattr(f, 'x'):
        f.x = 0
    print(f.x)
    f.x+=1


f()#输出1
f()#输出2
def f():
    class haha:
        cnt=1
        def __init__(self):
            print("haha"*haha.cnt)
            haha.cnt+=1
    if not hasattr(f, 'x'):
        f.x = 0
    if not hasattr(f,'ha'):
        f.ha=haha
    print(f.x)
    f.ha()
    f.x+=1


f()#输出0和haha
f()#输出1和hahahaha





你可能感兴趣的:(python)