浅谈Python3函数命名空间与作用域

前一章节讲述了命名空间和作用域的知识,现在我们来谈一谈Python3函数的命名空间吧。

一、函数名的本质

函数名的本质是一个存储函数体本身的十六进制地址的变量,也可以说是一个指向函数体本身的指针,如下所示:

def hello():
    print("hello")

print(hello)

# 控制台输出:
<function hello at 0xcc485270>

既然函数名本质上是一个变量,那么就可以赋值给其它变量,如下所示:

def hello():
    print("hello")

a = hello
print(a)

# 控制台输出:
<function hello at 0xcc485270>

函数的调用,就是在函数名后面加一对英文圆括号,即函数名(),亦可理解为函数地址(),如下所示:

def hello():
    print("hello")

a = hello
print(a)
# 通过变量a调用函数hello()
a()

# 控制台输出:
<function hello at 0xcc485270>
hello

二、函数命名空间

三、函数作用域

四、global与nonlocal

发布了26 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_35844043/article/details/104074353