函数补充
原创...小于 1 分钟
eval()函数
功能:将字符串 str 当成有效的表达式来求值并返回计算结果。语法: eval(source[, globals[, locals]]) -> value
a = 10
b = 20
c = eval("a+b")
print(c) # 30
nonlocal 关键字
nonlocal
用来在内部函数中,声明外层的局部变量。
a = 100
def outer():
b = 10
def inner():
nonlocal b # 声明外部函数的局部变量
print("inner b:", b) # 10
b = 20
inner()
print("outer b:", b) # 20
outer()
global 关键字
global
函数内声明全局变量,然后才使用全局变量
a = 100
def outer():
a = 10
def inner():
global a # 声明全局变量
print("inner a:", a) # 100
a = 1000
inner()
print("outer a:", a) # 10
outer()
print("a:", a) # 1000
Powered by Waline v2.15.7