3

Does Python disallow using print (or other reserved words) in class method name?

$ 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

Change print to other name (e.g., aprint) will not produce the error. It is surprising to me if there's such restriction. In C++ or other languages, this won't be a problem:

#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");
}
Oxdeadbeef
  • 1,033
  • 2
  • 11
  • 26
  • In C++, `printf` isn't a reserved word. Try naming a method `int`, and you'll find that C++ disallows it, but Python allows it, since it isn't a reserved word in Python. – user2357112 Oct 17 '16 at 22:25

2 Answers2

5

The restriction is gone in Python 3, when print was changed from a statement to a function. Indeed, you can get the new behaviour in Python 2 with a future import:

>>> 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

As a style note, it's unusual for a python class to define a print method. More pythonic is return a value from the __str__ method, which customises how an instance will display when it is printed.

>>> class A(object):
...     def __str__(self):
...         return "I'm A"
...     
>>> a = A()
>>> print(a)
I'm A
wim
  • 338,267
  • 99
  • 616
  • 750
0

print is a reserved word in Python 2.x, so you can't use it as an identifier. Here is a list of reserved words in Python: https://docs.python.org/2.5/ref/keywords.html.

UltraJ
  • 467
  • 1
  • 10
  • 20