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