zoukankan      html  css  js  c++  java
  • Python变量状态保持四种方法

    Python状态保持

    全局 global

    1 def tester(start):
    2     global state
    3     state = start
    4     def nested(label):
    5         global state
    6         print(label,state)
    7         state += 1
    8     return nested # 都声明为全局,只会保存一个副本,会覆盖
        

    非本地 nonlocal

    1 def tester(start):
    2     state = start
    3     def nested(label):
    4         nonlocal state
    5         print(label,state)
    6         state += 1
    7     return nested # Python3 主流 但是作用域只能是嵌套作用域
           

    类 class

    1 class nested():
    2     def __init__(self,state):
    3         self.state = state
    4     def __call__(self,label):
    5         print(self.state,label)
    6         self.state += 1 # 有点老了

    函数属性 函数名.变量名

    1 def tester(start):
    2     def nested(label):
    3         print(label,nested.state)
    4         nested.state += 1
    5     nested.state = start
    6     return nested  # 未曾用过的黑魔法,这回就知道了
  • 相关阅读:
    java wait方法
    thread join
    AtomicReference 原理
    exchanger java另一种栅栏
    CyclicBarrier 栅栏 原理,应用场景
    信号量Semaphore
    FutureTask 解析
    CountDownLatch
    java 双端队列 Deque
    lockInterruptibly 和lock 原理
  • 原文地址:https://www.cnblogs.com/SunQi-Tony/p/9240623.html
Copyright © 2011-2022 走看看