python高级语法

python的枚举用法

  • 枚举类的值不要重复
  • 枚举类不要实例化
# -*-coding:utf-8-*-
# Author:Lai

from enum import Enum,unique

@unique
class VIP(Enum):
    BLACK = 1
    YELLOW = 2
    BLUE = 3


if __name__ == "__main__":
    #枚举类型
    print(VIP.BLACK)

    #枚举类型的值int
    print(VIP.BLACK.value)

    #枚举类型的名称str
    print(VIP.BLACK.name)

    #通过类型的值int转枚举类型
    print(VIP(1))

    #循环枚举类型
    for v in VIP:
        print(v)

python的闭包

def test1():
    a = 10
    def inner():
        print(a)
    return inner

def test2():
    a = 10
    def inner():
        # a是一个局部变量
        a = 5
        print(a)
    return inner


if __name__ == "__main__":
    f1 = test1()
    print(f1.__closure__[0].cell_contents)  #10
    
    f2 = test2()
    print(f2.__closure__)  #None

python全局变量的赋值 与 闭包变量的赋值

1.全局变量的赋值

# -*-coding:utf-8-*-
# Author:Lai

orgin = 0

def outer(step:int):
    # 特别注意
    global orgin
    new_orgin = orgin + step
    orgin = new_orgin

if __name__ == "__main__":
    outer(3)
    print(orgin)
    outer(5)
    print(orgin)
    outer(7)
    print(orgin)

2.闭包变量的赋值

# -*-coding:utf-8-*-
# Author:Lai

def outer():
    orgin = 0
    def inner(step):
        # 特别注意
        nonlocal orgin
        new_orgin = orgin + step
        orgin = new_orgin
        print(orgin)
    return inner

if __name__ == "__main__":
     f = outer()
     print(f.__closure__[0].cell_contents)
     f(3)
     print(f.__closure__[0].cell_contents)
     f(5)
     print(f.__closure__[0].cell_contents)
     f(7)
     print(f.__closure__[0].cell_contents)
posted @ 2020-08-23 00:04  lilied  阅读(160)  评论(0编辑  收藏  举报