Data classes

Let's now discuss a new feature that was added in Python 3.7—data classes. First of all, data classes are just syntactic sugar (simpler syntax). The end result is just an ordinary instance of a class, and it can be achieved with normal classes, just in a few more lines. As the name implies, data classes are a simple way to write data-focused classes.

What do we mean by data-focused? Basically, data classes have the __repr__ and __init__ methods defined out of the box. By specifying additional parameters, such as eq, order, and frozen, we can make a data class generate additional boilerplate methods—such as equality (eq), smaller/greater (order), and add immutability (frozen). One caveat is that the default initiation function only assigns specified values. For any additional logic, you can write a __post_init__ method—it will be executed upon initiation.

Let's take a look at the following example. We're defining our Person class (yes, again) as a data class. For that, we need to import a dataclass object from the standard library. Next, we define the class, using the dataclass object as a decorator (remember, we discussed decorators in Chapter 3, Functions). In that class, we declare two variables, adding their data type (yes, it is required—but won't be enforced at runtime):

from dataclasses import dataclass

@dataclass
class Person:
name:str
age:int

That's it! This is way shorter than our previous solution. Let's try them:

>>> P1 = Person('Pippi', 11)
>>> P2 = Person('Pippi', 11)
>>> K = Person('Kalle', 10)

>>> P1 == K
False

>>> P1 == P2
True

Not only are we able to generate instances of the class, but they have a default, built-in equality mechanism! Data classes are a neat solution if you need to compare instances—they will save you quite a few lines of code (and, thus, reduce the chances of making an error). 

Having learned so much about classes, let's now put our new skill to the test by using classes to simulate an ecosystem.

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

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