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โ€ฆโ€ฆโ€ฆ๐Ÿ˜


Let's keep in touch!

Stay updated with my latest posts and news. I share insights, updates, and exclusive content.

Unsubscribe anytime. By subscribing, you share your email with @yokee-ss-hh and accept our Terms & Privacy.

Give a Pawfive to this post!


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

Start writing about what excites you in tech โ€” connect with developers, grow your voice, and get rewarded.

Join other developers and claim your FAUN.dev() account now!

Avatar

yokesh Chowdary

Backend developer, Clarivate

@yokee-ss-hh
Loves Backend web development, Consistently playing with Datastructures and algorithms.
Developer Influence
38

Influence

4k

Total Hits

3

Posts