Rather than inspecting the types of the objects that are being passed to your method, you would make it so that the objects implement the logic themselves.
Lets take an example: the len
function.
A native implementation would be:
def len(x):
if type(x) == str:
# compute the length of a string
elif type(x) == list:
# compute the length of a list
else:
#
But this has a few caveats
- You couldn't support
len
in your own objects without re-implementinglen
- It's a huge, unreadable, mess
And, most importantly, the OO-part about it, it means that your implementation of str
is scattered across your codebase: the code for computing its length is here, the code for slicing it is somewhere else...
Instead, a much saner design is what's used in Python:
def len(x):
return x.__len__()
It's then up to each object to implement the __len__
method itself. The len
function just asks the object for its length.
To a certain extent, you can consider this a "Strategy Pattern"