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