Dataclasses in Python

avatar

Dieses Feature gibt es seit Python3.7. Datenklassen in Python sind Klassen die eine Reihe vorgefertigter Funktionen mitbringen und man so überflüssigen Code sparen kann. Es entfallen u.a. das erstellen eines Konstruktors und es werden Standardgemäß Funktionen wie hash, eq,repr automatisch erstellt.
Datenklassen können auch mit Attributen erweitert werden, wie z.B. frozen, order, eq, ... Damit kann man bei Bedarf z.B. die eq Funktion überschreiben oder eine Klasse Konstant machen.
Außerdem müssen bei den Klassenvariablen ihre Datentypen explizit mit angegeben werden.

Hier mal ein Beispiel.

from dataclasses import dataclass

# The dataclass with the frozen attribute
# frozen means it is a const class
# It cannot be changed after it's creation
@dataclass(frozen=True, order=True)
class Person:
    name : str
    age : int
    sex : str
    birthday : Date

# regular class
class Date:

    def __init__(self,day,month,year):
        self.day = day
        self.month = month
        self.year = year

    def toString(self):
        return f'{self.day}.{self.month},{self.year}'

if __name__ == '__main__':
    # Let's play a bit with dataclasses!
    manfred = Person('Manfred',35,'m',Date(23,8,1977).toString()) # dataclass does not need a constructor
    vivian = Person('Vivian',28,'w',Date(17,12,1965).toString())

    print(manfred) # __repr__ is default implemented
    # vivian.age = 56 <--- does not work, because of Frozen
    print(manfred > vivian) # lt,le,gt,ge works because of Order
    print(hash(manfred))



0
0
0.000
1 comments
avatar

Congratulations @ozelot47! You received a personal badge!

Happy Hive Birthday! You are on the Hive blockchain for 3 years!

You can view your badges on your board and compare yourself to others in the Ranking

0
0
0.000