Previous: Refactoring in Object-Oriented Programming
There are numerous functions in Python that perform a task or calculate a result on certain types of objects without being methods on the underlying class. Some of these are closely related to class definitions, allowing us to use a functional style of programming with the underlying complex objects. For examples: len(), reversed(), enumerate()
functions.
In Python, not all built-in functions internally call a method on a class, but most of them do, especially when dealing with objects and special methods.
Typically, built-in functions like len()
, str()
, int()
, iter()
, etc., internally call special methods of the object (i.e., methods that start and end with double underscores).
len(my_obj)
internally calls myobj.__len__()
.str(obj)
internally calls obj._str__()
.reversed()
internally calls the __**reversed__**()
method.Because of this, we can override these object methods in the custom class to control what the built-in function will returns for the instance of your class.
Class List:
# Intersection in OOP and function
class List:
def __init__(self, args):
# args: allow functions to accept an arbitrary number of arguments.
# can be a list, string, integer, etc.
self._list = args
# Override the __len__() method
def __len__(self):
return 3
def main():
my_list = List([1, 2, 3, 4, 5])
print("Length of List:", len(my_list))
main()
Output:
Length of List: 3
Class String: