Python dunder methods cheat sheet
Python dunder methods cheat sheet
Here's a comprehensive cheat sheet on Python's dunder (double underscore) methods:
What are dunder methods?
In Python, dunder methods are special methods that start and end with double underscores (e.g., __init__
, __str__
). These methods allow you to overload operators, control the behavior of your objects, and interact with other parts of the Python language. Dunder methods are a key feature of Python's object-oriented programming system.
List of dunder methods:
__init__(self[, *args], **kwargs)
: Initializes the object. __del__(self)
: Destroys the object (not guaranteed to be called). __repr__(self)
: Returns a string representation of the object (used by print()
and other functions). __str__(self)
: Returns a human-readable string representation of the object. __bytes__(self)
: Converts an object to bytes (Python 3.x only). __hash__(self)
: Returns the hash value of the object. __eq__(self, other)
, __ne__(self, other)
, __lt__(self, other)
, etc.: Define equality and comparison operators for your class. __add__(self, other)
, __sub__(self, other)
, ...: Overload basic arithmetic operations (+, -, *, /). __getitem__(self, key)
, __setitem__(self, key, value)
, __delitem__(self, key)
: Implement indexing and assignment for your class (e.g., lists, dictionaries). __call__(self, *args, **kwargs)
: Allow instances of the class to be called like functions. __getattr__(self, name)
, __getattribute__(self, name)
, __setattr__(self, name, value)
, __delattr__(self, name)
**: Implement attribute access and manipulation (e.g., property-like behavior). __dir__(self)
: Return a list of valid attributes for the object. __len__(self)
: Returns the length of the object (used by len()
function). __contains__(self, item)
: Check if an item is in the object (used by in
operator).
Best practices:
Use dunder methods sparingly and only when necessary. Document your dunder methods with a clear description of what they do. Be careful when overloading operators; it can lead to unexpected behavior or ambiguities if not done correctly.Common use cases for dunder methods:
Creating custom container classes (e.g., lists, dictionaries). Implementing operator overloading (e.g., +, -, *, /) for a specific class. Providing custom string representation (__str__()
) or serialization (__bytes__()
) for an object. Defining custom equality and comparison operators (__eq__
, __ne__
, etc.). Implementing indexing and assignment (__getitem__
, __setitem__
) for a class.
By mastering Python's dunder methods, you'll gain deeper insight into the language and be able to create more sophisticated and reusable code.
Python dunder methods list
I'll respond in English for this one-off exception.
Python's dunder methods (also known as magic methods) are special methods that provide a way to overload operators, implement object serialization, and perform other custom behaviors. Here's a comprehensive list of Python's dunder methods:
Operator Overloading
__add__(self, other)
- + operator __sub__(self, other)
- - operator __mul__(self, other)
- * operator __div__(self, other)
- / operator
__mod__(self, other)
- % operator __pow__(self, other)
- ** operator __eq__(self, other)
- == operator __ne__(self, other)
- != operator __lt__(self, other)
- < operator __le__(self, other)
- <= operator __gt__(self, other)
- > operator __ge__(self, other)
- >= operator
Comparison
__hash__(self)
- Custom hash function for objects __contains__(self, item)
- Contains method for lists, dictionaries, etc.
Indexing
__getitem__(self, key)
- [] indexing (e.g., my_list[0]
) __setitem__(self, key, value)
- [] assignment (e.g., my_list[0] = 42
)
Serialization
__str__(self)
- Custom string representation for objects __repr__(self)
- Custom representation for debugging purposes __bytes__(self)
- Convert object to bytes
Conversion
__int__(self)
- Convert object to integer __long__(self)
- (Legacy) Convert object to long integer __float__(self)
- Convert object to float __complex__(self)
- Convert object to complex number __index__(self)
- Convert object to integer or long
Other
__init__(self, ...)
- Initialize an object __del__(self)
- Destroy an object (destructor) __getattribute__(self, name)
- Attribute access for objects __setattr__(self, name, value)
- Set attribute for objects __delattr__(self, name)
- Delete attribute for objects
Python's dunder methods provide a way to extend the language and make it more flexible and customizable. By implementing these special methods, you can create custom behaviors and data structures that interact seamlessly with built-in Python types.
Keep in mind that this list is not exhaustive, as there are other special methods defined by Python. However, this should give you a good starting point for understanding the various dunder methods available in Python.