2022.08.10 DAY24
1. 函数基础
1. eval()函数
- 将字符串str作为有效的表达式来求值并返回计算结果。
- 语法:
- eval(source[ , globals[ , locals]]) -> value
- 参数:
- source:一个python表达式或函数compile返回的代码对象。
- globals:可选。必须是dictionary。
- locas:可选。任意映像对象。
示例:
def test_eval():
str = "print('string')"
eval(str)
a = 10
b = 20
c = eval("a+b")
print("c = {0}".format(c))
if __name__ == '__main__':
test_eval()
结果:
string
c = 30
2. 递归函数
- 自己调用自己
- 终止条件
- 表示递归什么时候结束。一般用于返回值,不再调用自己。
- 递归步骤
- 把第n步的值和n-1步相关联。
示例:
def test_01(n):
""" 递归函数 """
print("*test01,n = ", n)
if(n == 0):
print("over...")
else:
test_01(n - 1);
print("*test01,n = ", n)
if __name__ == '__main__':
test_01(5)
结果:
*test01,n = 5
*test01,n = 4
*test01,n = 3
*test01,n = 2
*test01,n = 1
*test01,n = 0
over...
*test01,n = 0
*test01,n = 1
*test01,n = 2
*test01,n = 3
*test01,n = 4
*test01,n = 5
递归算阶乘:
def factorial(number):
""" 递归算阶乘 """
if number == 1:
return 1;
else:
return number * factorial(number - 1);
if __name__ == '__main__':
print("5! = {0}".format(factorial(5)))
结果:
5! = 120
3. 嵌套函数(内部函数)
- 嵌套函数:在函数内部定义的函数
- 使用说明:
- 封装 - 数据隐藏
- 外部无法访问’嵌套函数’
- DRY
- 可以让函数内部避免重复代码
- 闭包
- 封装 - 数据隐藏
示例:
def test_02():
""" 嵌套函数 """
print('outer running')
def inner01():
""" 只能内部可用 """
print('inner01 running')
inner01()
if __name__ == '__main__':
test_02()
结果:
outer running
inner01 running
4. nonlocal 关键字
- nonlocal 用来声明外层的局部变量
- global 用来声明全局变量
示例:
def outer():
b = 10
def inner():
nonlocal b # 声明外部函数的局部变量
print("inner b:",b)
b = 20
inner()
print("outer b:", b)
if __name__ == '__main__':
outer()
结果:
inner b: 10
outer b: 20
5. LEGB规则
- Python在查找名称时,是按照LEGB规则查找的:
- Local --> Enclosed --> Global --> Built in
- Local 函数或者类的方法内部
- Enclosed 嵌套函数
- Global 模块中的全局变量
- Built in Python为自己保留的特殊名称
测试LEGB:
str = "global"
def outer():
str = "outer"
def inner():
str = "inner"
print(str)
inner()
outer()