python - 在函数内部使用函数
问题描述
我是 python 新手,正在学习函数,但是在函数内部使用函数让我感到困惑。例子是
def print_lyrics():
print( "I am a lumberjackm and I'm ok." )
print( "I sleep all night and I work all day." )
def repeat_lyrics():
print_lyrics()
print_lyrics()
print(repeat_lyrics)
对此的输出是<function repeat_lyrics at 0x000002F5569D5E50>
,我不知道这意味着什么。我只想能够打印repeat_lyrics
功能并让它使用该print_lyrics
功能。有人可以帮我吗?:)
解决方案
在 Python 中,函数是与其他所有事物一样的对象。
因此,您可以将函数分配给变量,将其打印等。要调用函数(甚至从分配给它的变量中),您可以在括号中传递一组参数,这就是调用函数的语法。
所以:
def hello():
print('hello')
# print a representation of the function object
print(hello)
# assign the function to a variable
bonjour = hello
# call the function (printing "hello")
hello()
# calling the function assigned to the variable (also printing "hello")
bonjour()
事实上,在 之后和bonjour = hello
之间没有区别,它们都只是名称,指向最初定义为 的完全相同的函数。bonjour
hello
hello
所以,你写的地方:
print(repeat_lyrics)
这没有错,因为它会打印函数,但您可能想执行它:
repeat_lyrics()
另请注意,未显式返回某些内容的函数将返回None
。所以:
print(repeat_lyrics())
将执行该函数,然后打印它返回的内容,因此它也会打印None
.
推荐阅读
- rust - Rust:错误[E0495]:由于闭包中的冲突要求,无法推断自动引用的适当生命周期
- sbt - 如何将 sbt-assembly 放入 artifactory 并让 sbt 检索它
- java - 缩短嵌套 lambda
- asp.net-core-webapi - asp.net core API 最佳实践控制器命名路由
- ruby-on-rails - Rspec shared_examples_for 跳过测试
- php - 何时在 Laravel 中使用 Repository vs Service vs Trait?
- java - 如何从包含多种对象类型的数组列表中实例化一个对象
- python - evdev - 终止读取循环
- linux - 仅提取文件名的 Shell 脚本
- c++ - 键盘不工作 - Arduino Uno - 与变量有关的多个错误