Python class definition syntax

PythonClass

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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 http://www.python.org/doc/newstyle/">new-style classes (deriving from object is optional in Python 3.x, since new-style classes are the default there).

Solution 3 - Python

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.

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.

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFalmarriView Question on Stackoverflow
Solution 1 - PythonRafe KettlerView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythonMittView Answer on Stackoverflow