Question

When using PyCharm (community edition) on my Windows 7, I can have a class like so:

class X:
    def __init__(self):
        self.x = 0
    def print(self):
        print('x:', x)

And use it normally:

>>> x = X()
>>> x.print()
0

This code runs with no problems. However, when I run the same code on my Ubuntu using gedit and terminal (python x_file.py), I get an error:

$ python main.py
  File "main.py", line 6
    def print(self):
            ^
SyntaxError: invalid syntax

Why the difference, am I allowed to have a method called print in a class, or is this just one of PyCharm's features?

Était-ce utile?

La solution

In python3 there is absolutely no problem, however in python2 there was a print statement which precludes you from using it as an identifier, including a method name.

It seems like you have python2 on Ubuntu and python3 on Windows, hence the difference.

If you want to avoid the print statement in python2 add:

from __future__ import print_function

At the top of your file and you should obtain python3's print function, thus allowing you to define a method called print, (see this documentation).


Also note that without the __future__ import and in python3 this line:

print('x:', x)

Outputs:

x: <value for x>

However in python2 without the special import you get:

('x:', <value for x>)

Because the (...) does not specify the arguments to the function but is interpreted as a tuple to be printed by the statement.

Autres conseils

By any chance your ubuntu python version is below 3 ? since Python 2 uses:

print "test"

and Python 3 uses:

print("test")

In python 2+ print is a special statement like break, return, raise and so on. You cannot override these by creating objects with the same name. In python 3+ print is a function and the argument is the string between parentheses. Builtin functions can be overridden in python so that's why you can define your own print (even outside your class) in python 3. In your particular example PyCharm is probably based on python 3 and on your ubuntu machine you have '2.something'.

Off-topic: overriding builtins is usually not a good idea.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top