Python Dunder
Python stores class variables in __dict__
from pprint import pprint
class HtmlDocument:
extension = 'html'
version = '5'
HtmlDocument.media_type = 'text/html'
pprint(HtmlDocument.__dict__)__str__
__eq__
Scenario:
Suppose you want to retrieve person data with respect to their age or add new user Or simply want to check if an object is same based on certain criteria.
Handling User Input: In user interfaces or user-driven applications, you may need to compare user-provided data with existing data.
Validating login credentials by comparing a user-provided username and password with stored values.
Checking if an email address or username is already in use during user registration.
Caching and Memorization: In performance optimization techniques like caching and memorization, you can compare input parameters to previously computed results to avoid redundant calculations.
We can method override equality method from base class.
We can improvise the code above to check if the comparison is done with an instance only to avoid situation like:
john = Person('John', 'Doe', 25) print(john == 20)
__hash__
if a class override __eq__ then objects are no more hash-able. If an object cannot be hashed, it cannot be used in mapping type such as dict or set.
__bool__ && __len__
To override default behavior of class to boolean response
If no boolean method then class will look for __len__ method.
References:
ChatGPT
pythontutorials.net
Last updated
Was this helpful?