3

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");
}
4

2 回答 2

5

当 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是从方法返回一个值,该__str__方法自定义实例在打印时的显示方式。

>>> class A(object):
...     def __str__(self):
...         return "I'm A"
...     
>>> a = A()
>>> print(a)
I'm A
于 2016-10-17T22:25:05.373 回答
0

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

于 2016-10-17T22:26:46.250 回答