Vermillion Vermillion - 26 days ago 5x
Python Question

Python function that behaves differently depending on the input object types

In Python, can I write a function that takes objects as inputs and performs different calculations depending on the types of the objects?

For example, say I have two classes: "circle" and "line". I define a circle object A with a radius and centre position, and a circle object B with a different radius and centre position. I then define a line object C with a direction vector and a point along the line.

I would like to write a function that calculates the intersection:

def intersect(obj1,obj2):
# Returns intersection of two geometric entities

If I input the two circles A and B, I want the function to return the area of intersection of A and B. But if I input circle A and line C, I want the output to be the points (if any) where the line crosses the circle. So intersect(obj1,obj2) will need to somehow read the class of obj1 and obj2, and act accordingly.


Yes, you can certainly detect the types of your Python objects and execute different behaviour based on that. The built-in type() method will provide the information you need.

I should stress that this is rather reverting to the procedural paradigm whereas what you may be better off doing in looking into object orientation (specifically polymorphism).

You can also return arbitrary types from a function, so returning the two-dimensional intersection of two circles in one case, and two points of intersection between a circle and line in another, is certainly doable as well.

Again, that's addressing the possibility, not the wisdom. It's certainly possible that I could try to cut down a giant Karri tree with a haddock, but the wisdom of such a move would be, at best, dubious.

By way of example, the following program shows how to return a different type of value, based on the type of the parameter passed in:

def fn(x):
    if type(x) is int:
        return 42
    if type(x) is list:
        return [3.14159,2.71828]
    return None


The output is, as expected: