Billy Sans Billy Sans - 3 years ago 86
Python Question

Overload Methods in Python (Workarounds)

A simplified version of my problem: I want to write a method in python that takes in one parameter, either a list of strings or my custom object which holds a list of strings. Then return the size of the list. The method is specifically for a user to call so I want it to be simple for the user (essentially I don't want two methods doing the same exact thing except for a single line of code and I don't want to import non python standard libraries)

I realize overloading is not possible in python like it is in Java.

What is a good way to go about this/what is the standard way? The solutions I have thought of are:

Write two different methods.
Write one method with two parameters and defaults, check for defaults move accordingly.
Write one method with one parameter, check what kind of object is passed in, move accordingly (not entirely sure if this type checking is possible)

From a design perspective if statements for each type of object I want to handle does not seem great in the long run, but I don't see any other solutions (besides separate methods)

Thank you for suggestions!

Answer Source

As alfasin suggested, you can implement a __len__ function for your object;

class A(object):
    def __init__(self, mylist):
        self.mylist = mylist
    def __len__(self):
        return len(self.mylist)

For more complex distinctions, you can use isinstance at the function level:

def myfunction(obj):
    if isinstance(obj, list):
        # when the object is a list
    elif isinstance(obj, MyClass):
        # when the object is something else
    else:
        raise ValueError('wrong type!')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download