Python special functions, also known as magic methods or dunder methods (short for “double underscore methods”), are predefined methods with special names that start and end with double underscores. These methods allow you to customize the behavior of your classes and objects in various scenarios. Here are some commonly used special functions in Python:
__init__(self, ...)
: This special function is the constructor method and is called when an object is created from a class. It initializes the object and sets its initial state.__str__(self)
: This method is called by the built-instr()
function and returns a string representation of the object. It is commonly used for human-readable output or debugging purposes.__repr__(self)
: This method is called by the built-inrepr()
function and returns a string representation of the object that can be used to recreate the object. It is typically used for a more detailed and unambiguous representation of the object.__len__(self)
: This method is called by the built-inlen()
function and returns the length of the object. It is commonly used for sequences or containers to provide the number of elements in the object.__getitem__(self, key)
: This method allows objects to support indexing and slicing operations. It is called when an element is accessed using square brackets ([]
).__setitem__(self, key, value)
: This method allows objects to support the assignment of values to elements using square brackets ([]
). It is called when an element is assigned a value.__delitem__(self, key): This method allows objects to support the
deletion of elements using thedel
statement. It is called when an element is deleted using square brackets ([]
).__iter__(self)
: This method enables objects to be iterable, allowing them to be used infor
loops. It should return an iterator object that defines the__next__()
method.__next__(self)
: This method is used in conjunction with the__iter__()
method to define the iteration behavior of an object. It should return the next item in the iteration sequence.__call__(self, ...)
: This method allows objects to be called as functions. It is called when the object is invoked with parentheses as if it were a function.
These are just a few examples of special functions in Python. There are many more special functions available for different purposes, such as arithmetic operations (__add__
, __sub__
, etc.), comparison operations (__eq__
, __lt__
, etc.), and more. By implementing these special functions in your classes, you can customize the behavior of your objects and make them behave like built-in types or interact with Python’s built-in functions and operators in a desired way.