0

I'm trying to get a grasp on the concept of polymorphism and I kind of understand what it is in the context of OOP, but I've read that it can also apply to procedural programming and I don't really understand how.

I know that there's a bunch of methods and operators in Python, for example, which already use polymorphism, but what function that I write would qualify as polymorphic? For example, would the function what_type below be considered polymorphic, because by definition it has different behaviour based on the data type of the parameter it takes in, or is this just a regular example of a function with conditional statements in it?

def what_type(input_var):
    'Returns a statement of the data type of the input variable'

    # If the input variable is a string
    if type(input_var) is str:
        this_type = "This variable is a string!"

    # If it's an integer
    elif type(input_var) is int:
        this_type = "This variable is an integer!"

    # If it's a float
    elif type(input_var) is float:
        this_type = "This variable is a float!"

    # If it's any other type
    else:
        this_type = "I don't know this type!"


    return this_type
Roscoe
  • 13
  • 1
  • 1
  • 4
  • 2
    I suggest you copy/paste the code using the special _code_ markdown feature of StackOverflow, rather than showing a screenshot. – Savir Oct 27 '16 at 23:19

2 Answers2

1

Perhaps it could be considered a rather uninteresting example of ad-hoc polymoriphism, but it isn't the sort of thing most people have in mind when they talk about polymorphism.

In addition to the OOP-style polymoriphism which you seem to be somewhat comfortable with, Python has an interesting protocol-based polymorphism. For example, iterators are objects which implement a __next__() method. You can write polymorphic functions which work with any iterator. For example, if you wanted to wrap two iterators into one which alternates between the two you could do something like this:

def alternate(source1,source2):
    for x,y in zip(source1,source2):
        yield x
        yield y

This could be applied to strings:

>>> for item in alternate("cat","dog"): print(item)

c
d
a
o
t
g

but it could be equally applied to e.g. two files that are open for reading.

The point of such polymorphic code is you really don't care what type of iterators are passed to it. As long as they are iterators, the code will work as expected.

Community
  • 1
  • 1
John Coleman
  • 51,337
  • 7
  • 54
  • 119
-1

what_type is checking the type of the argument and deciding how to handle it by itself. It's not polymorphism nor oop.

In oop, what_type should not concern the concrete type of the argument and the argument should treat type-specific behavior. So, what_type should be written like:

def what_type(input_var):
    input_var.print_whats_myself()
kaitoy
  • 1,545
  • 9
  • 16