Python 类定义语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4109552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python class definition syntax
提问by Falmarri
Is there a difference between
之间有区别吗
class A:
...
and
和
class A():
...
I just realized that a couple of my classes are defined as the former and they work just fine. Do the empty parenthesis make any difference?
我刚刚意识到我的几个类被定义为前者,并且它们工作得很好。空括号有什么区别吗?
采纳答案by Ignacio Vazquez-Abrams
The latter is a syntax error on older versions of Python. In Python 2.x you should derive from objectwhenever possible though, since several useful features are only available with new-style classes(deriving from objectis optional in Python 3.x, since new-style classes are the default there).
后者是旧版本 Python 的语法错误。但是,在 Python 2.x 中,您应该object尽可能从派生,因为一些有用的功能仅适用于新式类(派生 fromobject在 Python 3.x 中是可选的,因为新式类是那里的默认值)。
回答by Rafe Kettler
While it might not be syntactically incorrect to use the empty parentheses in a class definition, parentheses after a class definition are used to indicate inheritance, e.g:
虽然在类定义中使用空括号在语法上可能没有错误,但类定义后的括号用于表示继承,例如:
class A(baseClass):
...
In Python, the preferred syntax for a class declaration without any base classes is simply:
在 Python 中,没有任何基类的类声明的首选语法很简单:
class A:
...
Don't use parentheses unless you are subclassing other classes.
不要使用括号,除非您要继承其他类。
The docs on the mattershould give you a better understanding of how to declare and use classes in Python.

