第十一章、高级语法与用法
文章目录
一、枚举
1.枚举其实就是一个类
-
枚举的定义:本质是类
-
导包:
-
from enum import Enum # 导入枚举对应的包 class VIP(Enum): yellow = 1 green = 2 black = 3 red = 4 print(VIP.yellow) # 结果: VIP.yellow
-
2.枚举的优势
- 字典和类定义的数据都是可变的,没有防止相同标签的出现
- 枚举是不可更改的
3.枚举类型,枚举名称与枚举值
-
获取枚举标签下所对应的值
-
对数据访问
-
from enum import Enum # 导入枚举对应的包 class VIP(Enum): yellow = 1 green = 2 black = 3 red = 4 print(VIP.yellow.value) # 结果: 1
-
对标签进行访问
-
from enum import Enum # 导入枚举对应的包 class VIP(Enum): yellow = 1 green = 2 black = 3 red = 4 print(VIP.yellow.name) # 结果: yellow
-
VIP.yellow.name和VIP.yellow的不同
-
from enum import Enum # 导入枚举对应的包 class VIP(Enum): yellow = 1 green = 2 black = 3 red = 4 print(type(VIP.yellow.name)) print(type(VIP.yellow)) # 结果: <class 'str'> <enum 'VIP'>
-
-
通过枚举名称获取枚举的值
-
from enum import Enum # 导入枚举对应的包 class VIP(Enum): yellow = 1 green = 2 black = 3 red = 4 print(VIP["yellow"]) # 结果: VIP.yellow
-
-
枚举的遍历:
-
from enum import Enum # 导入枚举对应的包 class VIP(Enum): yellow = 1 green = 2 black = 3 red = 4 for ele in VIP: print(ele) # 结果: VIP.yellow VIP.green VIP.black VIP.red
-
4.枚举的比较运算
- ==,同一个类型可以进行比较
- 大小比较不可进行
- 身份比较
is
可以
5.枚举注意事项
- 枚举类型的标签是不可以相同的,但是数值可以
- 枚举的遍历时,若数值相同,你们第二个hi是第一个标签的别名
6.枚举转换
from enum import Enum
# 导入枚举对应的包
class VIP(Enum):
yellow = 1
green = 2
black = 3
red = 4
a = 1
print(VIP(a))
# 结果:
VIP.yellow
7.枚举总结
-
强制要求数字作为数值时可以用
Intenum
-
from enum import IntEnum class VIP(IntEnum): yellow = 1 green = 2 black = "str" red = 4 # 结果:存在字符 ValueError: invalid literal for int() with base 10: 'str'
-
-
不能有相同值时
-
from enum import IntEnum,unique @unique class VIP(IntEnum): yellow = 1 green = 2 black = 1 red = 4 # 结果:有相同值 ValueError: duplicate values found in <enum 'VIP'>: black -> yellow
-
二、对象与闭包
1.一切皆对象
- 高阶编程和函数式编程有关
- 闭包
- 函数:
- 在别的语言中,函数只是一段可执行的代码,并不是对象。
- 可以把函数当做另外一个函数的参数传递到函数中去
- 函数:
2.什么是闭包:和变量的作用域有关
-
# 闭包 def curve_pre(): a = 25 def curve(x): return a*x*x return curve # curve 函数在外部不可以调用,会报错,作用域只在外层函数的内部 f = curve_pre() print(f(2)) # 结果: 100
-
闭包 = 函数+环境变量
-
闭包的意义:将现场保护起来
3.闭包的误区
-
def f1(): a = 10 def f2(): # a被认为是局部变量 a = 20 print(a) print(a) f2() print(a) f1() # 结果:不属于闭包 10 20 10
4.闭包解决问题
- 闭包的作用:
- 不是必不可少的东西
- 记住上一次变量的状态
origin = 0
def f1(pos):
def f2(step):
nonlocal pos
new_step = pos + step
pos = new_step
return new_step
return f2
f = f1(origin)
print(f(1))
print(f(2))
print(f(3))
# 结果:
1
3
6
global 变量
:全局变量不会被误认为成局部变量
s):
def f2(step):
nonlocal pos
new_step = pos + step
pos = new_step
return new_step
return f2
f = f1(origin)
print(f(1))
print(f(2))
print(f(3))
结果:
1
3
6
`global 变量`:全局变量不会被误认为成局部变量
`nonlocal 变量` :闭包变量,不会被误认为成局部变量