簡體   English   中英

在Python 2.7中返回打印函數

[英]Return a print function in Python 2.7

如何在Python 2.7中返回打印功能? 在Python 3中,您可以鍵入return print(True) ,但是在Python 2.7中,當我嘗試return print True時會收到無效的語法錯誤。 我是Python的新手。

在Python 2.x中, print不是函數,而是關鍵字。 可能的最佳解決方案是按如下方式導入類似3.x的打印行為:

from __future__ import print_function

p = print         # now you can store the function reference to a variable
p('I am a function now!')

>>> I am a function now!

def get_print():
    return print   # or return it :)

get_print()

>>> <function print>

在Python 2.7中這是不可能的,因為print不是函數,它是保留字*。 您可以像這樣輕松地為其創建函數:

def printf(x):
  print x

然后,您可以做自己想做的事情:

return (printf(True))

但是您必須重命名。

*這是在python 3上更優雅地解決的問題之一。

print是Python 2中的語句,而不是函數,不能以這種方式使用。 相反,您需要這樣做:

from __future__ import print_function
def foo():
    return print(True)
foo()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM