Dunder methods are double underscored methods that are used to emulate the behavior of built-in types. They are predefined methods that simplify many operations that can be performed on a class instance, like __init__(), __str__(), __call__() etc. These methods are very helpful because they are used in binary operations, assignment operations, unary and binary comparison operations.
Note: For more information, refer to Dunder or magic methods in Python
__getitem__ and __setitem__
There are getter and setter methods as a part of these magical methods. They are implemented by
__setitem__() methods. But, these methods are used only in indexed attributes like arrays, dictionaries, lists e.t.c. Instead of directly accessing and manipulating class attributes, it provides such methods, so these attributes can be modified only by its own instances and thus implements abstraction.
Instead of making class attributes as public, these methods make them private, provide validation that only correct values are set to the attributes and the only correct caller has access to these attributes.
Let’s take the example of a bank record of a person. It contains balance, transaction history, and other confidential records as part of it. Now, this bank record needs to be handled as a built-in data type to facilitate many operations. There are several methods which need access for balance and transaction history. If they directly modify the balance, they might end up inserting null values, or negative values that are very vulnerable. So, the
__setitem__() helps in presenting the details securely.
The balance is : 100 The new balance is : 300 The no. of transactions are: 2 The new balance is : 600 The no. of transactions are: 3 The transaction history is: [100, 200, 300]
Here you can see, how easy to implement
setBalance(), just by implementing
__setitem__() methods. Also, it takes care of validation of balance and transaction history.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course