在Python中使用print作为类方法名称

Oxd*_*eef 2 python printing reserved

Python是否禁止print在类方法名称中使用(或其他保留字)?

$ cat a.py

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

$ python a.py

File "a.py", line 3
  def print(self):
          ^
  SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

更改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");
}
Run Code Online (Sandbox Code Playgroud)

wim*_*wim 5

当打印从语句更改为函数时,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
Run Code Online (Sandbox Code Playgroud)

作为样式注释,python类定义print方法是不常见的.更多pythonic是从方法返回一个值,该值__str__可以自定义实例打印时的显示方式.

>>> class A(object):
...     def __str__(self):
...         return "I'm A"
...     
>>> a = A()
>>> print(a)
I'm A
Run Code Online (Sandbox Code Playgroud)