揭秘 Python 函数不为人知的一面
2023-12-04 04:48:05
通常我们定义一个函数,然后调用该函数时,函数相关的代码才开始执行。可是很多人并不知道,当我们定义函数时,一些代码就开始执行了。今天就来说说函数这个不为人知的一面。
先看一段代码:
def outer_function():
print("outer_function() called")
def inner_function():
print("inner_function() called")
inner_function()
运行这段代码,你会看到输出:
outer_function() called
inner_function() called
你可能以为是调用 outer_function()
才执行了 inner_function()
,其实不是,定义 outer_function()
时,inner_function()
就已经执行了。
这是因为 Python 函数在定义时就会执行,而不是在调用时才执行。这被称为函数的立即执行性。
函数的立即执行性还体现在函数嵌套上。函数嵌套是指在一个函数内部定义另一个函数。
def outer_function():
print("outer_function() called")
def inner_function():
print("inner_function() called")
return inner_function
inner_function = outer_function()
inner_function()
运行这段代码,你会看到输出:
outer_function() called
inner_function() called
你可能以为是调用 outer_function()
才执行了 inner_function()
,其实不是,定义 outer_function()
时,inner_function()
就已经执行了。
这是因为 Python 函数在定义时就会执行,而不是在调用时才执行。
函数的立即执行性还体现在函数闭包上。函数闭包是指在一个函数内部定义另一个函数,并且内部函数可以使用外部函数的变量。
def outer_function():
x = 10
def inner_function():
print("x =", x)
return inner_function
inner_function = outer_function()
inner_function()
运行这段代码,你会看到输出:
x = 10
你可能以为是调用 outer_function()
才执行了 inner_function()
,其实不是,定义 outer_function()
时,inner_function()
就已经执行了。
这是因为 Python 函数在定义时就会执行,而不是在调用时才执行。
函数的立即执行性是一个非常重要的概念,它可以用来实现很多高级的编程技巧。比如,你可以用函数的立即执行性来实现单例模式。
def singleton():
instance = None
def get_instance():
nonlocal instance
if instance is None:
instance = Singleton()
return instance
return get_instance
Singleton = singleton()
instance1 = Singleton()
instance2 = Singleton()
print(instance1 is instance2)
运行这段代码,你会看到输出:
True
这表明 instance1
和 instance2
是同一个对象,也就是单例模式。
函数的立即执行性是一个非常强大的工具,你可以用它来实现很多高级的编程技巧。如果你想成为一名优秀的 Python 程序员,那么你必须掌握函数的立即执行性。