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

时间:2016-10-17 22:21:42

标签: 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()

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

2 个答案:

答案 0 :(得分: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

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

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

答案 1 :(得分:0)

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