TigerTV.ru
TigerTV.ru

Reputation: 1086

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?

Upvotes: 4

Views: 6585

Answers (3)

Robᵩ
Robᵩ

Reputation: 168636

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()

Upvotes: 10

Ankit Malik
Ankit Malik

Reputation: 90

I tried your code on Python 3 like this:

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

a = MyClass()
a.print()

It worked !!

Output:

MyClass

Running your code as is gives me Syntax Error. Because of missing parenthesis in print. Also, note that print is a reserved keyword in Python 2 but a built-in-function in Python 3.

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95957

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

Upvotes: 8

Related Questions