在 Python 中打印函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14330016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing a function in Python
提问by Captn Buzz
I'm just starting to learn Python, and I'm currently reading a book that is teaching me,
and in the book a function just like the one I have made below prints the actual text that is defined in the first function, but when I run my script it says:
<function two at 0x0000000002E54EA0>as the output. What am I doing wrong? Did I install the wrong Python or something? I downloaded the 3.3.0 version
我刚刚开始学习 Python,我目前正在阅读一本教我的书,书中的一个函数就像我在下面所做的那样打印第一个函数中定义的实际文本,但是当我运行我的脚本,它说:
<function two at 0x0000000002E54EA0>作为输出。我究竟做错了什么?我安装了错误的 Python 还是什么?我下载的是3.3.0版本
Here is my code:
这是我的代码:
def one():
print ("lol")
print ("dood")
def two():
print (one)
print (one)
print (two)
采纳答案by Tim
Your functions already print text, you don't need to print the functions. Just call them (don't forget parenthesis).
您的函数已经打印文本,您不需要打印函数。只需调用它们(不要忘记括号)。
def one():
print ("lol")
print ("dood")
def two():
one()
one()
two()
回答by Althaf Hameez
You call a function in the following syntax
您使用以下语法调用函数
def two():
one()
one()
two()
What goes inside the parenthesis is the input parameters which you would learn later in the book.
括号内的内容是您将在本书后面学习的输入参数。
回答by poncho
you are printing the function itself, not what the function should print, maybe you wanted to print this way
您正在打印函数本身,而不是函数应该打印的内容,也许您想以这种方式打印
def one():
print ("lol")
print ("dood")
def two():
print one()
print one()
print two()
the output would be: lol dood
输出将是:lol dood
回答by ApproachingDarknessFish
The printing happens inside your function. The function itself is a sequence of code to be executed. In your case, this code is printing "lol"and "dood"to the screen. In order to execute this code, you callthe function simply by typing its name:
打印发生在您的函数内部。函数本身是一个要执行的代码序列。在您的情况下,此代码正在打印"lol"并显示"dood"在屏幕上。为了执行此代码,您只需键入其名称即可调用该函数:
def one():
print("lol")
print("dood")
def two():
one() #simply type the function's name to execute its code
one()
two()
Calling printon the function itself prints a the location in memory of the code that the function executes when it is called, hence your garbled output.
调用print函数本身会打印函数在调用时执行的代码在内存中的位置,因此输出是乱码。
回答by Michael Mior
This is not the answer you are looking for…
这不是您要找的答案……
But in interest of completeness, suppose you did want to print the code of the function itself. This will only work if the code was executed from a file (not a REPL).
但出于完整性考虑,假设您确实想打印函数本身的代码。这仅在代码是从文件(而不是 REPL)执行时才有效。
import inspect
code, line_no = inspect.getsourcelines(two)
print(''.join(code))
That said, there aren't many good reasons for doing this.
也就是说,这样做的理由并不多。

