gpt4 book ai didi

python - Python 3.x 中新的 print 函数相对于 Python 2 的 print 语句有什么优势?

转载 作者:IT老高 更新时间:2023-10-28 21:38:15 25 4
gpt4 key购买 nike

我多次听说 print 作为函数 (3.x) 比作为语句 (2.x) 要好。但为什么呢?

我喜欢它是一个声明,主要是因为它允许我少输入两个字符(即括号)。

我很想看看 print 语句只是没有削减它的一些情况,并且功能更优越。

最佳答案

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

关于python - Python 3.x 中新的 print 函数相对于 Python 2 的 print 语句有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com