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.
# Code without __eq__
class Person:
def __init__(self, first_name, last_name, age):
self.first_name = name
self.last_name = last_name
self.age = age
Shariq = Person("Shariq", "Khan", 28)
Akshay = Person("Akshay", "Kumar", 28)
Shariq == Akshay #False
# Code with __eq__
class Person:
def __init__(self, first_name, last_name, age):
self.first_name = name
self.last_name = last_name
self.age = age
def __eq__(self, other):
return self.age = self.other
Shariq = Person("Shariq", "Khan", 28)
Akshay = Person("Akshay", "Kumar", 28)
Shariq == Akshay #True
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)
# Code with __eq__
class Person:
def __init__(self, first_name, last_name, age):
self.first_name = name
self.last_name = last_name
self.age = age
def __eq__(self, other):
if isinstance(other,Person):
return self.age = self.other
Shariq = Person("Shariq", "Khan", 28)
Akshay = Person("Akshay", "Kumar", 28)
Shariq == Akshay #True
__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.
# Hash implementation if you implement __eq__
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if isinstance(other,Person):
return self.age == other.age
def __hash__(self):
return hash(self.age)
Shariq = Person("Shariq", 28)
Akshay = Person("Akshay", 28)
Shariq == Akshay
print(hash(Shariq))
s = {Shariq}
__bool__ && __len__
To override default behavior of class to boolean response
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __bool__(self):
if self.age < 18 or self.age > 65:
return False
return True
if __name__ == '__main__':
person = Person('Shariq', 16)
print(bool(person)) # False
If no boolean method then class will look for __len__ method.
class Payroll:
def __init__(self, length):
self.length = length
def __len__(self):
print('len was called...')
return self.length
if __name__ == '__main__':
payroll = Payroll(0)
print(bool(payroll)) # False
payroll.length = 10
print(bool(payroll)) # True
References:
ChatGPT
pythontutorials.net
Last updated
Was this helpful?