Data classes

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.py
from dataclasses import dataclass

@dataclass
class 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) / 2


body = Body('Ball', 19, 3.1415)
print(body.kinetic_energy()) # 93.755711375 Joule
print(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 me to calculate its kinetic energy (using the renowned formula Ek=½mv2). Notice that name is supposed to be a string, while mass and speed are both floats, and both are given a default value. It's also interesting that I didn't have to write any __init__ method, it's done for me by the dataclass decorator, along with methods for comparison and for producing the string representation of the object (implicitly called on the last line by print).

You can read all the specifications in PEP557 if you are curious, but for now just remember that data classes might offer a nicer, slightly more powerful alternative to named tuples, in case you need it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset