当类不继承任何内容时,从命令行调用 python 脚本会出现语法错误,这是为什么?
这个问题(对我来说)没有任何实际意义。我只是偶然发现了这一点,我很好奇其背后的机制。我得到了以下示例脚本:
#!/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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Python 2.7.2 语法,以下语法不正确:
它应该是
或者
很可能您正在使用两个不同版本的 Python 解释器,并且由于某种原因,其中一个解释器允许无效语法,而另一个则不允许。
According to the Python 2.7.2 grammar, the following syntax is incorrect:
It should be either
or
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.
不应使用括号,例如:
除非您想从另一个类继承,否则
You should not use the parenthesis
unless you want to inherit from another class, e.g.: