【发布时间】:2016-10-17 22:21:41
【问题描述】:
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");
}
【问题讨论】:
-
在 C++ 中,
printf不是保留字。尝试命名一个方法int,你会发现C++不允许它,但是Python允许它,因为它不是Python中的保留字。