Sobes.tech
Junior — Middle

Can you explain the concept of function polymorphism and its application in programming?

sobes.tech AI

Answer from AI

Function polymorphism is the ability of a function to work with different data types or objects, providing a unified interface for various implementations. In programming, this allows for writing more flexible and extensible code.

In Python, polymorphism is achieved, for example, through:

  • Function overloading (via different arguments, although in Python this is implemented manually)
  • Using duck typing — the function accepts an object and calls methods without explicitly checking its type
  • Inheritance and method overriding in classes

Example of duck typing:

def process(item):
    item.do_something()

class A:
    def do_something(self):
        print("A does something")

class B:
    def do_something(self):
        print("B does something")

process(A())  # Outputs: A does something
process(B())  # Outputs: B does something

Thus, one process function works with different object types if they implement the required method.