Python function that behaves differently depending on the input object types
<p>In Python, can I write a function that takes objects as inputs and performs different calculations depending on the types of the objects?</p>

<p>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.</p>

<p>I would like to write a function that calculates the intersection:</p>

<pre><code>def intersect(obj1,obj2):
    # Returns intersection of two geometric entities
</code></pre>

<p>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.</p>

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

<p>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).</p>

<p>You can also return <em>arbitrary types</em> 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.</p>

<p>Again, that's addressing the <em>possibility</em>, 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.</p>

<p>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:</p>

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

print(fn(1))
print(fn([1,2]))
print(fn(42.7))
</code></pre>

<p>The output is, as expected:</p>

<pre><code>42
[3.14159,2.71828]
None
</code></pre>

python oop linear-algebra