Python class definition syntax

前端 未结 2 1607
抹茶落季
抹茶落季 2020-12-02 11:42

Is there a difference between

class A:
    ...

and

class A():
    ...

I just realized that a couple of my

相关标签:
2条回答
  • 2020-12-02 12:17

    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:

    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.

    0 讨论(0)
  • 2020-12-02 12:31

    The latter is a syntax error on older versions of 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).

    0 讨论(0)
提交回复
热议问题