🤔 Ever heard of Dunder methods (__init__, __repr__, __eq__, ...) in Python?

You want to learn more about them?

🧵 This one is for you👇
1️⃣ Dunder methods are set of predefined methods that can enrich your classes.

They're called dunder methods because of double under score at the beginning and at the end of their name

Class that implements them can mimic behavior of built-in types like int, str, list, ...
2️⃣ __init__ is the most used one.

It's used to construct objects from class A - a constructor

You can define which arguments it takes

Inside it attributes of newly created instance are set
3️⃣ Change objects representation

__str__ - this one is used when conversion to string is requested - printable representation

__repr__ - official representation, it's great if you can just copy it to your code to create new object with the same values
4️⃣ Operator overloading - enable object comparison

__eq__ - a == b
__ne__ - a != b
__lt__ - a < b
__gt__ - a > b
__le__ - a <= b
__ge__ - a >= b
__add__ - a + b
...

You also need to implement them if you want to make your objects sortable
5️⃣ Make objects callable

To make object callable you need to implement __call__
6️⃣ Make a generator class

You need to implement __next__ and __iter__ methods
7️⃣ To access and set attributes the same way as for dictionary you can implement

__getitem__ - a['key']
__setitem__ - a['key'] = 'value'
8️⃣ You can find all available methods and more about Python data model here:

https://docs.python.org/3/reference/datamodel.html
You can follow @jangiacomelli.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.