【问题标题】:Using print as class method name in Python在 Python 中使用 print 作为类方法名
【发布时间】:2016-10-17 22:21:41
【问题描述】:

Python 是否不允许在类方法名中使用print(或其他保留字)?

$ cat a.py

import sys
class A:
    def print(self):
        sys.stdout.write("I'm A\n")
a = A()
a.print()

$ python a.py

File "a.py", line 3
  def print(self):
          ^
  SyntaxError: invalid syntax

print 更改为其他名称(例如aprint)不会产生错误。如果有这样的限制,我感到很惊讶。在 C++ 或其他语言中,这不是问题:

#include<iostream>
#include<string>
using namespace std;

class A {
  public:
    void printf(string s)
    {
      cout << s << endl;
    }
};


int main()
{
  A a;
  a.printf("I'm A");
}

【问题讨论】:

  • 在 C++ 中,printf 不是保留字。尝试命名一个方法int,你会发现C++不允许它,但是Python允许它,因为它不是Python中的保留字。

标签: python printing reserved


【解决方案1】:

当 print 从语句更改为函数时,限制在 Python 3 中消失了。事实上,您可以通过未来的导入获得 Python 2 中的新行为:

>>> from __future__ import print_function
>>> import sys
>>> class A(object):
...     def print(self):
...         sys.stdout.write("I'm A\n")
...     
>>> a = A()
>>> a.print()
I'm A

作为一种风格说明,python 类定义print 方法是不寻常的。更多 Pythonic 是 return 来自 __str__ 方法的值,它自定义实例在打印时的显示方式。

>>> class A(object):
...     def __str__(self):
...         return "I'm A"
...     
>>> a = A()
>>> print(a)
I'm A

【讨论】:

    【解决方案2】:

    print 是 Python 2.x 中的保留字,因此不能将其用作标识符。以下是 Python 中的保留字列表:https://docs.python.org/2.5/ref/keywords.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 2010-09-18
      • 2013-03-19
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      相关资源
      最近更新 更多