Magic methods, also known as dunder (short for "double underscore") methods, allow you to customize the behavior of your Python objects. They are always surrounded by double underscores (e.g., __init__, __str__).
Here's a list of some commonly used magic methods and how you can use them in your classes:
Basic Customizations:
__init__(self, ...): Constructor method.__del__(self): Destructor method. Called when the instance is about to be destroyed.__repr__(self): Represents the object. Should return a valid Python expression if possible.__str__(self): Called by print() and str().Comparison:
__eq__(self, other): Implements equality.__ne__(self, other): Implements inequality.__lt__(self, other): Implements less than.__le__(self, other): Implements less than or equal to.__gt__(self, other): Implements greater than.__ge__(self, other): Implements greater than or equal to.Arithmetic:
__add__(self, other): Implements addition.__sub__(self, other): Implements subtraction.__mul__(self, other): Implements multiplication.__floordiv__, __mod__, __pow__, etc.Type Conversion:
__int__(self): Implements type conversion to int.__float__(self): Implements type conversion to float.__bool__(self): Implements type conversion to bool. If not defined, objects are always True unless they define a __len__ method that returns False or 0.Containers:
__len__(self): Implements the built-in function len().__getitem__(self, key): Implements accessing an item using obj[key].__setitem__(self, key, value): Implements setting an item using obj[key] = value.__delitem__(self, key): Implements deleting an item using del obj[key].__iter__(self): Implements iteration over the container.__contains__(self, item): Implements membership test operators (in and not in).Here's an example of a class that uses some of these magic methods:
class ComplexNumber: def __init__(self, real, imag): self.real = real self.imag = imag def __repr__(self): return f"ComplexNumber({self.real}, {self.imag})" def __str__(self): return f"{self.real} + {self.imag}i" def __add__(self, other): return ComplexNumber(self.real + other.real, self.imag + other.imag) def __eq__(self, other): return self.real == other.real and self.imag == other.imag # Usage: c1 = ComplexNumber(3, 2) c2 = ComplexNumber(1, 7) print(c1) # 3 + 2i print(c1 + c2) # 4 + 9i print(c1 == c2) # False These are just a few examples. There are many more magic methods available in Python that allow you to define custom behavior for your objects in various scenarios.
dynamics-crm-2011 msgbox sublimetext2 jenkins-groovy java-stream fluent telephony dst spring-boot-configuration php-shorttags