Special Methods

Carson West

Constructors

Special Methods

These are methods in Python classes that begin and end with double underscores (__), also known as “dunder” methods. They define how objects of the class behave in certain contexts. They’re crucial for creating classes that interact seamlessly with built-in Python features and other libraries.

Examples and Functionality:

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

my_dog = Dog("Buddy", "Golden Retriever")
class Dog:
    # ... __init__ ...
    def __str__(self):
        return f"Dog named {self.name}, breed: {self.breed}"

print(my_dog) # Calls __str__
class Dog:
    # ... __init__ ... __str__ ...
    def __repr__(self):
        return f"Dog('{self.name}', '{self.breed}')"

print(repr(my_dog)) # Calls __repr__
class MyList:
    def __init__(self, data):
        self.data = data
    def __len__(self):
        return len(self.data)

my_list = MyList(1,2,3)
print(len(my_list))

Further Exploration:

This is not an exhaustive list, but covers some of the most frequently used special methods. The Python documentation provides a complete reference.