zoukankan      html  css  js  c++  java
  • 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
        x=haha()#定义一个haha类型的变量
        print(f.x)
        f.x+=1
    
    
    f()#输出0和haha
    f()#输出1和haha
    
    

    在函数f()内部定义了一种类型haha,haha有一个静态变量cnt。每次执行函数f()都要对haha类型进行加载(也就是初始化类型的静态变量)
    可以用如下方式实现保持每次调用f()函数使用同一个haha。

    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
    
    
  • 相关阅读:
    代码管理工具SonarQube的搭建和使用
    WebFlux Logs日志
    WebFlux WebClient异常处理
    WebFlux- WebClient(二)
    WebFlux- WebClient(一)
    WebFlux-Server-Sent Event服务器推送事件
    Reactive Stack
    Flink
    Gradle
    springboot
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/7927331.html
Copyright © 2011-2022 走看看