Skip to content Skip to footer

Introducing Python Classes and Dataclasses


Quick Success Data Science

A hands-on guide for beginners

A classroom with empty, well-organized white desks in rows.
(mche-lee-PC91Jm1DlWA-unsplash)

If you’re going to do any serious programming with Python, you’ll need to understand object-oriented programming and the concept of a class and a dataclass. In this Quick Success Data Science article, you’ll get a quick and painless introduction to all three, including what they’re for, how you use them, and why you need them.

Object-oriented programming (OOP) is a language model that reduces code duplication and makes code easier to update, maintain, and reuse. As a result, most commercial software is now built using OOP.

Whereas procedural programming is built around actions and logic, OOP is built around data structures, known as objects, that consist of data and functions (called methods) that act on the data. Objects are built from classes, which are like blueprints for the objects.

A class is a data type, and when you create an object of that data type, it is also known as an instance of that class. The process of setting the initial values and behaviors of the instance is called instantiation.

As instances of a class, objects allow you to create multiple copies with the same structure but potentially different data. For example, if you’re building a space combat game, you can conveniently bundle the attributes of a certain spaceship, like its size, speed, and armament, with the methods that control its flight and weapons operation. Then, when you create a new spaceship of that type, you only need to worry about giving it a unique name.

Because Python is an object-oriented programming language, you’ve already been using objects and methods defined by other people. But unlike languages such as Java, Python doesn’t force you to use OOP for your programs. It provides ways to encapsulate and separate abstraction layers using other approaches such as procedural or functional programming.

Having this choice is important. If you implement OOP in small programs, most of them will feel over-engineered. To paraphrase computer scientist Joe Armstrong, “The problem with object-oriented languages…



Source link