【问题标题】:Python: Sending the print function as a parameterPython:将打印函数作为参数发送
【发布时间】:2014-01-31 17:57:03
【问题描述】:

我的教授提到可以将 print 等函数作为参数传递,但是当我尝试并实际实现它时,出现语法错误。这是我在这里想念的小东西吗?

 def goTime(sequence, action):
    for element in sequence:
       action(element)

 def main():
    print("Testing Begins")
    test = list ( range( 0 , 20, 2) ) 
    goTime(test, print)
    print("Testing Complete")

运行以下命令时,我收到以下语法错误:

goTime(test, print)
                 ^
SyntaxError: invalid syntax

如果我定义自己的使用 print 的函数,它会像这样工作:

def printy(element):
   print(element)

def goTime(sequence, action):
   for element in sequence:
      action(element)

def main():
   print("Testing Begins")
   test = list ( range( 0 , 20, 2) ) 
   goTime(test, printy)
   print("Testing Complete")

【问题讨论】:

  • 哪个版本的python? print只是3中的一个函数。
  • @roippi 您也可以使用from __future__ import print_function 来获取早期版本。
  • 呸,我使用的是旧版本。愚蠢的错误,谢谢大家。
  • 请注意:Python2.7 不仅仅是 python 的旧版本。仍在大量使用:)

标签: python


【解决方案1】:

在 Python 3 中可以开箱即用。然而,在 Python 2.7 中,您可以这样做:

from __future__ import print_function
def foo(f,a):
    f(a)

foo(print,2)
2

请注意,在 Python2.7 中,在您执行 from __future__ import print_function 之后,您将无法再将 print 用作关键字:

>>> from __future__ import print_function
>>> print 'hi'
  File "<stdin>", line 1
    print 'hi'
             ^
SyntaxError: invalid syntax

虽然我认为您的教授只是想指出 Python 中的函数是一等公民(即:对象),它们可以作为任何其他变量传递。不过他举了一个有争议的例子:)

希望这会有所帮助!

【讨论】:

  • 我认为您不需要 print_function 周围的刻度。
  • @MarkRansom 大声笑,绝对不需要。对此感到抱歉:)
【解决方案2】:

您不能在 Python2 中传递 print,因为它是关键字而不是函数。在 Python3 中是可能的。

您可以尝试从未来导入新的打印功能。检查这个问题:

How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?

然后你就可以把它当成一个函数来使用了。

【讨论】:

    【解决方案3】:

    你可以试试sys.stdout

    import sys
    
    def printy(element):
        sys.stdout.write(str(element)+'\n')
    

    【讨论】:

      【解决方案4】:

      在 python2 中,您可以将 print 包装在包装函数中并传递:

      def PrintWrapper(arg):
          print(arg)
      
      def MyFunc(x, func):
          func(x)
      
      # call the function with the wrapper as an argument
      MyFunc("Hello world", PrintWrapper)
          
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-28
        • 2021-06-04
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        • 2021-07-07
        • 2015-03-31
        相关资源
        最近更新 更多