Sobes.tech
Junior — Middle

Explain the concept of duck typing and how it differs from static typing in programming.

sobes.tech AI

Answer from AI

Duck typing is a programming concept where the type of an object is determined not by its class or interface, but by the presence of certain methods and properties. If an object behaves like a "duck" (has the necessary methods), it is considered suitable.

Difference from static typing:

  • In static typing, types are checked at compile time, and objects must explicitly conform to certain types.
  • In duck typing, the check occurs at runtime, and only interface compatibility (methods/properties) matters, not inheritance or declared types.

Example in Python (duck typing):

class Duck:
    def quack(self):
        print("Quack")

class Person:
    def quack(self):
        print("I can quack like a duck")

def make_it_quack(thing):
    thing.quack()

make_it_quack(Duck())    # Quack
make_it_quack(Person())  # I can quack like a duck

Here, the function does not care about the object's type, only about the presence of the quack method.

Explain the concept of duck typing and how it differs… - sobes.tech