duck_typing.py

#!/usr/bin/python3
# ==================================================================
# Duck typing
# If it walks like a duck and quacks like a duck, it's a duck.
# ------------------------------------------------------------------
# Title: Python Tutorial: Duck Typing and Asking Forgiveness,
#        Not Permission (EAFP)
# From:  www.youtube.com/watch?v=x3v9zMX1s4sython3
# ==================================================================

class Duck:

    def quack(self):
        print('Quack, Quack!')

    def fly(self):
        print('Flap, Flap!')

class Person:

    def quack(self):
        print("I'm quacking like a Duck!")

    def fly(self):
        print("I'm flapping my arms!")

## non-pythonic way
##def quack_and_fly(thing):
##    # not a duck type
##    if isinstance(thing,Duck):
##        thing.quack()
##        thing.fly()
##    else:
##         print('This is not a Duck!')
##    print()

## pythonic way
def quack_and_fly(thing):
    try:
        thing.quack()
        thing.fly()
    except AttributeError as e:
        print(e)
    print()


d = Duck()

quack_and_fly(d)

p = Person()

quack_and_fly(p)