首页 > 解决方案 > 在函数内部使用函数

问题描述

我是 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功能。有人可以帮我吗?:)

标签: pythonfunction

解决方案


在 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之间没有区别,它们都只是名称,指向最初定义为 的完全相同的函数。bonjourhellohello

所以,你写的地方:

print(repeat_lyrics)

这没有错,因为它会打印函数,但您可能想执行它:

repeat_lyrics()

另请注意,未显式返回某些内容的函数将返回None。所以:

print(repeat_lyrics())

将执行该函数,然后打印它返回的内容,因此它也会打印None.


推荐阅读