跳至主要內容

函数补充

刘春龙原创...小于 1 分钟Python教程文档

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