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 and get more readers

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.
Stats
12

Influence

770

Total Hits

3

Posts