Certainly! Special methods, also known as "dunder" methods (short for "double underscore"), allow you to define how objects of your classes behave with built-in operations. Here are some common examples:
1. __init__
The constructor method, called when an object is created.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Usage
person = Person("Alice", 30)
2. __str__
Defines the string representation of an object, used by the print() function.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
# Usage
person = Person("Alice", 30)
print(person) # Outputs: Alice, 30 years old
3. __repr__
Defines the official string representation of an object, used by the repr() function and in the interactive interpreter.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
# Usage
person = Person("Alice", 30)
print(repr(person)) # Outputs: Person(name='Alice', age=30)
4. __eq__
Defines equality comparison using the == operator.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
# Usage
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
print(person1 == person2) # Outputs: True
5. __len__
Defines behavior for the built-in len() function.
class MyList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
# Usage
my_list = MyList([1, 2, 3])
print(len(my_list)) # Outputs: 3
6. __getitem__
Defines behavior for indexing (e.g., obj[key]).
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index]
# Usage
my_list = MyList([1, 2, 3])
print(my_list[1]) # Outputs: 2
7. __enter__ and __exit__
Used to define context managers for resource management (with the with statement).
class MyContext:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
# Usage
with MyContext():
print("Inside the context")
Conclusion
These special methods allow you to customize the behavior of your objects in Python, making them more intuitive and integrated with the language's features. If you have any specific questions about these methods or need more examples, feel free to ask!
