Join us

Data Classes 😈 in python (part-1)

python = ‘king’ 😘

python = ‘king’ 😘

Let’s start Data Classes 💃that uses dataclasses module

In a normal concrete class, we want to define a constructor and __repr__ to make the custom representation of the object when object is passed as parameter to print() function.

Am I only the one who hates writing long constructor method in the class ? Am I only the one who hates the memory representation of the object when i print the object as print(‘my-object’) ?

If you guys feels my pain! Cheers dude , You are in the right place ! 🍒

Let’s start Data Classes 💃that uses dataclasses module

In a normal concrete class, we want to define a constructor and __repr__ to make the custom representation of the object when object is passed as parameter to print() function. Look at the code below !

The above code gives output as,

Do you think the above code is more complex to write and understand ??

Let’s see the same type of code using Data class

output of the above code :

Do you see the output, it is so simple . Dataclasses uses a constructor internally and it has it’s own custom __repr__ method.

Another important feature of dataclass is 2 objects of a dataclass with same content in them always gives ‘True’ on ‘==’ operator. While Normal concrete class objects gives ‘False’

Let’s assume that i have 2 objects each in both dataclass and normal concrete class with same data as,

If I use ‘==’ operator on objects of their respective classes .Can you guess what it will return ? ‘True’ / ‘False’

output of the above code :

Dataclass objects with same data returns ‘True’ on ‘==’ operator and Concrete class objects with same data returns ‘False’ on ‘==’ operator.

Follow , clap and share if you find this blog helpful !

DataClasses part-2 will post soon………😍


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

Avatar

yokesh Chowdary

Backend developer, Clarivate

@yokee-ss-hh
Loves Backend web development, Consistently playing with Datastructures and algorithms.
User Popularity
24

Influence

2k

Total Hits

3

Posts