" 本文字数:1016 字 ||
阅读时间:3 分钟"
一切皆对象
先我们来理解下 Python 中的函数
def hi(name="yasoob"):
return "hi " + name
print(hi())
# output: 'hi yasoob'
# 我们甚可以将一个函数赋值给⼀个变量,如
greet = hi
# 我们这没有在使小括号,因为我们并不是在调⽤hi函数
# 是在将它放在greet变量里头。我们尝试运行下这个
print(greet())
# output: 'hi yasoob'
# 如果我们删掉旧的hi函数,看看会发什么!
del hi
print(hi())
#outputs: NameError
print(greet())
#outputs: 'hi yasoob'
Python进阶
一切皆对象 33
在函数中定义函数
在函数中定义函
在函数中定义函数
刚才那些就是函数的基本知识了。我们来让你的知识更进一步。在 Python 中我们可以在一个函数中定义另一个函数:
def hi(name="yasoob"):
print("now you are inside the hi() function")
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
print(greet())
print(welcome())
print("now you are back in the hi() function")
hi()
#output:now you are inside the hi() function
# now you are in the greet() function
# now you are in the welcome() function
# now you are back in the hi() function
# 上⾯展示了⽆论何时你调⽤hi(), greet()和welcome()将会同时被调⽤。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,⽐如:
greet()
#outputs: NameError: name 'greet' is not defined
那现在我们知道了可以在函数中定义另外的函数。也就是说:我们可以创建嵌套的函数。
现在你需要再多学一点,就是函数也能返回函数。
从函数中返回函数
其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:
def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet
else:
return welcome
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
#上⾯清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个
print(a())
#outputs: now you are in the greet() function
再次看看这个代码。在 if/else 语句中我们返回 gree t和 welcome,而不是greet() 和 welcome()。
为什么那样?
这是因为当你把一对小括号放在后,这个函数就会执行;然而如果你不放括号在它后,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。
让我再稍微多解释点细节。
当我们写下a = hi(),hi()会被执行,由于name参数默认是yasoob,所以函 数greet被返回了。如果我们把语句改为a = hi(name = "ali"),那么welcome函数 将被返回。我们还可以打印出hi()(),这会输出now you are in the greet() function。
将函数作为参数传给另一个函数
def hi():
return "hi yasoob!"
def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func())
doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
# hi yasoob!