简体   繁体   English

Python的类中的print函数

[英]Python's print function in a class

I can't execute print function in the class: 我无法在类中执行print函数:

#!/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 . 在Python 2中, print是一个关键字 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. 在Python 3中, print内置函数 ,而不是关键字。 So methods, for example, can have the name print . 因此,例如,方法可以具有名称print

If you are using Python 2 and want to override its default behavior, you can import Python 3's behavior from __future__ : 如果您正在使用Python 2并希望覆盖其默认行为,则可以从__future__导入Python 3的行为:

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). 您正在使用Python 2(除非您有充分的理由,否则您不应该使用它)。

In Python 2, print is a statement, so print is actually a reserved word. 在Python 2中, print是一个语句,因此print实际上是一个保留字。 Indeed, a SyntaxError should have been thrown when you tried to define a function with the name print , ie: 实际上,当您尝试使用名称print定义函数时, 应该抛出SyntaxError,即:

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. 所以,我很好奇你正在使用的Python 2的确切版本。 the above output was from a Python 2.7.13 session... 以上输出来自Python 2.7.13会话......

So note, in Python 3: 请注意,在Python 3中:

>>> class A:
...    def print(self):
...       print('A')
...
>>> A().print()
A

I tried your code on Python 3 like this: 我在Python 3上尝试过你的代码:

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. 另请注意,print是Python 2中的保留关键字,但是Python 3中的内置函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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