These methods provide a way to customize the behavior of objects in various scenarios like comparison, iteration, and attribute access. In this tutorial, youll learn how to use Python special method lookup to understand what happens when an object is accessed using its attributes or methods.
When you call an attribute or method on an object, Python first checks if that attribute exists as a regular variable in the current scope (local variables, global variables, etc.). If it doesn’t find anything, then it looks for special methods with names starting and ending with double underscores. These are called dunder methods because of their naming convention.
For example, lets say you have a class named `Person`:
# Defining a class named Person
class Person:
# Defining a constructor method with a parameter named name
def __init__(self, name):
# Assigning the value of the parameter name to the attribute name of the current instance
self.name = name
# Defining a method named __repr__ which returns a string representation of the current instance
def __repr__(self):
# Using string formatting to return a string with the name of the class and the dictionary of attributes of the current instance
return f"<{type(self).__name__} {self.__dict__}>"
# Defining a method named __str__ which returns a string representation of the current instance
def __str__(self):
# Using the str() function to convert the dictionary of attributes of the current instance into a string
return str(self.__dict__)
When you call `print(person)`, Python first checks if there’s a variable named “person”. If it doesn’t find anything, then it looks for special methods. In this case, the `__repr__()` and `__str__()` dunder methods are called to get string representations of the object.
The `__repr__()` method is used when you print an object using Pythons built-in repr() function or when it appears in a list, tuple, or dictionary. The `__str__()` method is used for other string operations like concatenation and formatting.
You can also define custom dunder methods to override the default behavior of objects. For example:
# Defining a class called Person
class Person:
# Defining a constructor method that takes in a name parameter
def __init__(self, name):
# Setting the name attribute of the Person object to the name parameter
self.name = name
# Defining a dunder method called __eq__ to override the default behavior of the == operator
def __eq__(self, other):
# Comparing the dictionaries of the two objects and returning True if they are equal, False otherwise
return self.__dict__ == other.__dict__
# Defining a dunder method called __ne__ to override the default behavior of the != operator
def __ne__(self, other):
# Using the __eq__ method to check if the two objects are not equal and returning the opposite value
return not (self == other)
In this example, the `__eq__()` and `__ne__()` dunder methods are defined to override the default behavior of equality and inequality operations. Instead of comparing object references or attribute values, these custom methods compare the entire dictionary of attributes for each object.
By using Python special method lookup, you can understand how objects behave when they’re accessed using their attributes or methods. This knowledge can help you write more efficient code by avoiding unnecessary function calls and optimizing performance.