Key 4: All objects can be made callable.
To reuse and group code for some task, we group it in the functions classes, and then call it with different inputs. The objects that have a __call__
attribute are callable and __call__
is the entry point. For the C class, tp_call
is checked in its structure:
Methods in classes are similar to functions, except that they are called with an implicit instance as a first argument. The functions are exposed as methods when they are accessed from the instance. The function is wrapped in a method class and returned. The method class stores instances in __self__
and function in __func__
, and its __call__
method calls __func__
with first argument as __self__
:
Using this logic, we can also collect methods that are needed from other classes in the current class, like the following code, instead of multiple inheritances if data attributes do not clash. This will result in two dictionary lookups for an attribute search: one for instance, and one for class.
When we call classes, we are calling its type, that is metaclass
, with class as a first argument to give us a new instance:
Similarly, when we call instances, we are calling their type, that is class, with instance as first argument: