Python(九) Python的高级语法与用法

时间:2023-01-30 19:55:06

本章节我们揭开Python进阶部分的高级特性,详细讲解枚举、闭包,并对函数式编程做出介绍

一、 枚举其实是一个类
from enum import Enum

#枚举类
class VIP(Enum):
    YELLOW = 1 #大写
    GREEN = 2
    BLACK = 3
    RED = 4 

print(VIP.YELLOW) # VIP.YELLOW

 

二、枚举和普通类相比有什么优势
 
1.不可变
2.去相同值

三、枚举类型、枚举名称与枚举值
from enum import Enum

#枚举类
class VIP(Enum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4 

# 枚举类型、枚举名字、枚举值
print(VIP.GREEN.value) # 2  枚举值
print(VIP.GREEN) # VIP.GREEN   枚举类型
print(VIP.GREEN.name) # GREEN  枚举名称

print(VIP['GREEN']) # VIP.GREEN 
print(type(VIP['GREEN'])) # <enum 'VIP'>

print(type(VIP.GREEN)) # <enum 'VIP'>
print(type(VIP.GREEN.name)) # <class 'str'>

# 遍历

for v in VIP:
    print(v)

# VIP.YELLOW
# VIP.GREEN
# VIP.BLACK
# VIP.RED

四、枚举的比较运算
 
from enum import Enum

#枚举类
class VIP(Enum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4 

# 枚举比较
r = VIP.GREEN == VIP.GREEN
print(r) # True

r = VIP.GREEN is VIP.GREEN
print(r) # True

# 枚举不可以做大小比较 不可以不同的枚举进行比较

 

五、枚举注意事项
 
枚举不可以相同的标签
 
值一样的话 枚举会把后面的当作前面的一个别名
from enum import Enum

#枚举类
class VIP(Enum):
    YELLOW = 1
    GREEN = 1
    BLACK = 3
    RED = 4 

print(VIP.GREEN) # VIP.YELLOW


for v in VIP:
    print(v)

# VIP.YELLOW
# VIP.BLACK
# VIP.RED

for v in VIP.__members__:
    print(v)

# YELLOW
# GREEN
# BLACK
# RED

for v in VIP.__members__.items():
    print(v)

# ('YELLOW', <VIP.YELLOW: 1>)
# ('GREEN', <VIP.YELLOW: 1>)
# ('BLACK', <VIP.BLACK: 3>)
# ('RED', <VIP.RED: 4>)

六、枚举转换
 
from enum import Enum

#枚举类
class VIP(Enum):
    YELLOW = 1
    GREEN = 1
    BLACK = 3
    RED = 4 

a = 1
print(VIP(a)) # VIP.YELLOW

七、枚举小结
 
from enum import Enum
from enum import IntEnum,unique

#枚举类

@unique   # 装饰器 不允许值相同 IntEnum 枚举值仅仅为int
class VIP(IntEnum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4 
# 23种设计模式 单例模式

八、进阶内容开场白
业务逻辑的开发者, 不考虑的太多的封装性
包、类库的开发者

九、一切皆对象
# 函数式编程
函数 是一个类
 
def a():
    pass

print(type(a)) # <class 'function'>

十、什么是闭包
#函数式编程
# 闭包 = 函数 +  环境变量
# 现场

def curve_pre():
    a=25 # 环境变量
    def curve(x):  # 函数
        return a*x*x
    return curve

a=10
f = curve_pre() 
print(f.__closure__) #(<cell at 0x00000210502553D8: int object at 0x000000005E5C6F40>,)
print(f.__closure__[0].cell_contents) # 25
print(f(2)) #100

 


十一、一个事例看看闭包
def f1():
    a = 10
    def f2():
        a = 20 # 被认为是一个局部变量 所以不是闭包
        print(a)
    print(a) # 10
    f2()    # 20
    print(a) # 10

f1()

# 10
# 20
# 10

十二、闭包的经典误区

十三、出个题,用闭包解决!
 
 
十四、我先用非闭包解决一下
origin = 0

def go(step):
    global origin
    new_pos = origin + step
    origin = new_pos
    return origin

print(go(2))
print(go(3))
print(go(6))

结果:
2
5
11

 

十五、再用闭包解决一下_
 
#闭包的环境变量 可以记忆 上一次调用的状态

origin = 0

def factory(pos):
    def go(step):
        nonlocal pos # 不是本地的 局部变量
        new_pos = pos + step
        pos = new_pos
        return new_pos
    return go

f = factory(origin)

print(f(2))
print(f(3))
print(f(5))

结果:
2
5
10

 

十六、小谈函数式编程

适合自己,函数式编程也不是高大上。