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?
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()
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With