December 2018
Beginner to intermediate
796 pages
19h 54m
English
Before we leave the OOP realm, there is one last thing I want to mention: data classes. Introduced in Python 3.7 by PEP557 (https://www.python.org/dev/peps/pep-0557/), they can be described as mutable named tuples with defaults
. Let's dive into an example:
# oop/dataclass.pyfrom dataclasses import dataclass@dataclassclass Body: '''Class to represent a physical body.''' name: str mass: float = 0. # Kg speed: float = 1. # m/s def kinetic_energy(self) -> float: return (self.mass * self.speed ** 2) / 2body = Body('Ball', 19, 3.1415)print(body.kinetic_energy()) # 93.755711375 Jouleprint(body) # Body(name='Ball', mass=19, speed=3.1415)
In the previous code, I have created a class to represent a physical body, with one method that allows ...
Read now
Unlock full access