Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's print function in a class

I can't execute print function in the class:

#!/usr/bin/python
import sys

class MyClass:
    def print(self):
        print 'MyClass'

a = MyClass()
a.print()

I'm getting the following error:

File "./start.py", line 9
    a.print()
          ^
SyntaxError: invalid syntax

Why is it happening?

like image 775
TigerTV.ru Avatar asked Nov 29 '22 22:11

TigerTV.ru


2 Answers

In Python 2, print is a keyword. It can only be used for its intended purpose. I can't be the name of a variable or a function.

In Python 3, print is a built-in function, not a keyword. So methods, for example, can have the name print.

If you are using Python 2 and want to override its default behavior, you can import Python 3's behavior from __future__:

from __future__ import print_function
class MyClass:
    def print(self):
        print ('MyClass')

a = MyClass()
a.print()
like image 118
Robᵩ Avatar answered Dec 05 '22 12:12

Robᵩ


You are using Python 2 (which you really shouldn't, unless you have a very good reason).

In Python 2, print is a statement, so print is actually a reserved word. Indeed, a SyntaxError should have been thrown when you tried to define a function with the name print, i.e.:

In [1]: class MyClass:
   ...:     def print(self):
   ...:         print 'MyClass'
   ...:
   ...: a = MyClass()
   ...: a.print()
  File "<ipython-input-1-15822827e600>", line 2
    def print(self):
            ^
SyntaxError: invalid syntax

So, I'm curious as to what exact version of Python 2 you are using. the above output was from a Python 2.7.13 session...

So note, in Python 3:

>>> class A:
...    def print(self):
...       print('A')
...
>>> A().print()
A
like image 41
juanpa.arrivillaga Avatar answered Dec 05 '22 14:12

juanpa.arrivillaga