What is the advantage of the new print function in Python 3.x over the Python 2 print statement?
我听过很多次,打印是一个函数(3.x)比它是一个语句(2.x)要好。但是为什么呢?
我非常喜欢它是一个语句,主要是因为它允许我少键入两个字符(即括号)。
我有兴趣看到一些情况下,打印语句只是不削减它,一个函数是优越的。
Rationale
The print statement has long appeared on lists of dubious language features that are to be removed in Python 3000, such as Guido's"Python Regrets" presentation [1]. As such, the objective of this PEP is not new, though it might become much disputed among Python developers.
The following arguments for a print() function are distilled from a python-3000 message by Guido himself [2]:
- print is the only application-level functionality that has a statement dedicated to it. Within Python's world, syntax is generally used as a last resort, when something can't be done without help from the compiler. Print doesn't qualify for such an exception.
- At some point in application development one quite often feels the need to replace print output by something more sophisticated, like logging calls or calls into some other I/O library. With a print() function, this is a straightforward string replacement, today it is a mess adding all those parentheses and possibly converting >>stream style syntax.
- Having special syntax for print puts up a much larger barrier for evolution, e.g. a hypothetical new printf() function is not too far fetched when it will coexist with a print() function.
- There's no easy way to convert print statements into another call if one needs a different separator, not spaces, or none at all. Also, there's no easy way at all to conveniently print objects with some other separator than a space.
- If print() is a function, it would be much easier to replace it within one module (just
def print(*args):... ) or even throughout a program (e.g. by putting a different function in__builtin__.print ). As it is, one can do this by writing a class with a write() method and assigning that to sys.stdout – that's not bad, but definitely a much larger conceptual leap, and it works at a different level than print.— PEP 3105 – Make print a function
从乔森的回答到斯文的回答,再加上:
您可以在不能使用
1 | [print(x) for x in range(10)] |
1 2 | 2.x: print >> my_file, x 3.x: print(x, file=my_file) |
新版本看起来更像python,不是吗?
函数版本的另一个优点是灵活性。例如,如果您想捕获所有用于调试目的的
1 2 3 | def print(*args, **kwargs): # whatever __builtins__.print(*args, **kwargs) |
我考虑过这个问题,不知道Python3版本的优点。但当我需要打印
1 | print *df.columns |
引发异常,而
1 | print(*df.columns) |
工作很好!如果您想在多个调用打印中使用相同的(可配置的)打印选项,可以将它们保存到字典中并作为
所以至少
您可以将内置的
1 2 3 4 5 6 7 8 9 10 11 | import os import sys def print(s): sys.stderr.write('Will now print ' + str(s) + '.' + os.linesep) sys.stdout.write(str(s) + os.linesep) print(['A', 'list']) # Output: # stderr: Will now print ['A', 'list']. # stdout: ['A', 'list'] |
您可以在lambda或函数调用等内部使用
1 2 | example_timeout_function(call=lambda: print('Hello world'), timeout=5) do_things(print_function=print) |