What other types of classes are there in Python?

Question:

I just found out about dataclasses and was reading some tutorials on how to use them. One tutorial described data classes as:

A data class is a class typically containing mainly data, although there aren’t really any restrictions.

What other types of classes are there besides data class? Are there also helpful tools/decorators for these classes, too? If data class is a class that contains mainly data, then a class containing mainly helper methods is something else?

Or should I think about using @dataclass decorator for any class I want to build as long as I’m using Python 3.7+?

Answers:

No, you should not decorate every class with @dataclass. Data class is just a container by its concept. You can use i.e. dictionary instead if you want but using regular class instead gives you opportunity to write your own accessors (setters/getters), have known and type-hinted properties etc, while dictionary will take anything your throw at it (be it key with typo or not, etc.). Having kind of guards helps keep your code clean and more strict and also makes all the linters like pylink, flake8 know what they are dealing with, which is always a GoodThing™.

Technically there’s no limitation what your dataclass can do as this is just a class as any other so you can write whatever you want but you want to keep the logic minimal and usually there are getters/setters or you can have __cmp__(), __eq__() or __ne__() implemented if your would benefit from it etc but not business logic.

Depending on language you use declaring/annotating/decorating class as dataclass usually does some additional magic to it and makes it have some common boilerplate code generated/implemented for you, like said accessors, hashing function, toString() etc etc.

Answered By: Marcin Orlowski

Here are a few types of classes, but there are other types and they might be defined differently across various journals or references.

  • Data classes: Classes that contain mainly data (This is what you are asking about)
  • Utility classes: Classes that contain helper methods that can be used across different parts of a program (This is the alternative you are looking for)
  • Abstract classes: Classes that provide an interface for other classes to inherit from… Cannot be instantiated on their own
  • Concrete classes: Classes that can be used to create objects
  • Decorator classes: Classes that can be used to modify the behavior of other classes

You are thinking of utility class, which is not really a data class.

Answered By: Michael Varney
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.