Override methods in Python

Override __getitem__() and __setitem__() Methods:

Python allows override [python]__getitem__()[/python] and [python]__setitem__()[/python] methods. We have already known that [python]__getitem__()[/python] is used to retrieve an item at a particular index. Similarly, [python]__setitem__()[/python] is used to set the value for a particular item at the specified index. Although they are well-defined for built-in types like list, tuple, string, etc. But for user-defined classes, we need to explicitly write their codes. By default, Python does not allow you to apply indexes on class objects but if you have defined the [python]__getitem__()[/python] and [python]__setitem__()[/python] methods in the class, then you can simply work with indices as with any other built-in type as shown in the following example:

Override in Operator:

We have seen that the in is a membership operator that checks whether the specified item is in the variable of built-in type or not (like string, list, dictionary, tuple, etc.) We can overload the same operator to check whether the given value is a member of a class variable or not.

To overload the in operator we have to use the function __contains__().

Override the __call__() Method:

The __call__() Method is used to overload call expressions. The __call__() Method is called Automatically when an instance of the class is called. It can be passed to any positional or keyword argument. Like other functions, the __call__() Method also supports all of the argument-passing modes. The __call__() Method can be declared as:

def __call__(self, [args...])