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");
}
1
  • 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. Commented Oct 17, 2016 at 22:25

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks for the info, and meanwhile, we can run this code to get the keywords of the current python version: print(keyword.kwlist)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.