当类不继承任何内容时,从命令行调用 python 脚本会出现语法错误,这是为什么?

发布于 2025-01-07 08:00:49 字数 581 浏览 4 评论 0原文

这个问题(对我来说)没有任何实际意义。我只是偶然发现了这一点,我很好奇其背后的机制。我得到了以下示例脚本:

#!/usr/bin/env python
"""
just an example
"""

class exampleClass():
    'this is just an example'


if __name__ == '__main__':
    print(__doc__)

在 eclipse 中运行此打印“只是一个示例”。但是,当我尝试在终端中运行它时,出现以下错误:

File "./temp.py", line 6
   class exampleClass():
                       ^
  SyntaxError: invalid syntax

现在,当我将示例脚本中的类更改为从 dict 继承

class exampleClass(dict):

并从命令行运行它时,它还会打印“只是一个示例”。 那么为什么类必须继承某些东西才能从命令行工作,而不是从 Eclipse 继承呢?

This question has (for me) no real implication. I just found this out by coincidence and I am curious about the mechanics behind it. I got the folling example script:

#!/usr/bin/env python
"""
just an example
"""

class exampleClass():
    'this is just an example'


if __name__ == '__main__':
    print(__doc__)

Running this in eclipse print "just an example". However, when I try to run this in the terminal I get the following error:

File "./temp.py", line 6
   class exampleClass():
                       ^
  SyntaxError: invalid syntax

Now, when I change the class in the example script to inherit from dict

class exampleClass(dict):

and run it from the commandline it also prints "just an example".
So why do classes have to inherit something to work from commandline, but not from eclipse?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烈酒灼喉 2025-01-14 08:00:49

根据 Python 2.7.2 语法,以下语法不正确:

class exampleClass():
    'this is just an example'

它应该是

class exampleClass:
    'this is just an example'

或者

class exampleClass(object): # or `dict' etc
    'this is just an example'

很可能您正在使用两个不同版本的 Python 解释器,并且由于某种原因,其中一个解释器允许无效语法,而另一个则不允许。

According to the Python 2.7.2 grammar, the following syntax is incorrect:

class exampleClass():
    'this is just an example'

It should be either

class exampleClass:
    'this is just an example'

or

class exampleClass(object): # or `dict' etc
    'this is just an example'

In all probability you're using two different versions of the Python interpreter, and for some reason one of the interpreters is allowing the invalid syntax and the other isn't.

绝影如岚 2025-01-14 08:00:49

不应使用括号,例如:

class exampleClass:
    pass 

除非您想从另一个类继承,否则

class exampleClass(object):
    pass 

You should not use the parenthesis

class exampleClass:
    pass 

unless you want to inherit from another class, e.g.:

class exampleClass(object):
    pass 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文