简体   繁体   中英

Using print as class method name in Python

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 (eg, 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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM