简体   繁体   English

Python class 定义语法

[英]Python class definition syntax

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?空括号有什么区别吗?

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, eg:虽然在类定义中使用空括号在语法上可能没有错误,但类定义后的括号用于表示继承,例如:

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 matter should give you a better understanding of how to declare and use classes in Python. 关于这个问题文档应该让你更好地理解如何在 Python 中声明和使用类。

The latter is a syntax error on older versions of Python.后者是旧版本 Python 的语法错误。 In Python 2.x you should derive from object whenever possible though, since several useful features are only available with new-style classes (deriving from object is optional in Python 3.x, since new-style classes are the default there).不过,在 Python 2.x 中,您应该尽可能从object派生,因为一些有用的功能仅适用于新样式类(从object派生在 Python 3.x 中是可选的,因为新样式类是那里的默认值)。

A class definition is a bit different from a function/method definition.类定义与函数/方法定义有点不同。

The parentheses in class definitions are for defining from which class you inherit.类定义中的括号用于定义您从哪个类继承。 You don't write def in front of it, and when you inherit from 'object' which is the default you don't need the parentheses for the definition.你不要在它前面写 def ,当你从默认的 'object' 继承时,你不需要括号来定义。

So you can write either:所以你可以写:

class C():

Or:或者:

class C:

Function/method definitions always take parentheses, even if you don't define parameters.函数/方法定义总是带括号,即使你没有定义参数。 If you don't use them, you'll get a SyntaxError.如果你不使用它们,你会得到一个 SyntaxError。

Later, after the definition of a class/function/method in the code, just writing the name will point you to the class/function/method.后面在代码中定义了一个类/函数/方法之后,只要写名字就会指向这个类/函数/方法。

If you want to call or access any of these, you'll need (), [], .如果您想调用或访问其中任何一个,您需要 ()、[]、. or whatever.管他呢。

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

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