# Python program to demonstrate
# duck typing
class Bird:
def fly(self):
print("fly with wings")
class Airplane:
def fly(self):
print("fly with fuel")
class Fish:
def swim(self):
print("fish swim in sea")
# Attributes having same name are
# considered as duck typing
for obj in Bird(), Airplane(), Fish():
obj.fly()
#output
#fly with wings
#fly with fuel
#Traceback (most recent call last):
#File "/home/854855e5570b9ce4a9e984209b6a1c21.py", line 20, in
#obj.fly()
#AttributeError: 'Fish' object has no attribute 'fly'
In this example, we can see a class supports some method we can modify it
or give them new functionality. Duck-typing emphasis what the
object can really do, rather than what the object is.
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
class Person:
def quack(self):
print("The person imitates a duck.")
def feathers(self):
print("The person takes a feather from the ground and shows it.")
def name(self):
print("John Smith")
def in_the_forest(duck):
duck.quack()
duck.feathers()
def game():
donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)
game()
class Person:
def help(self):
print("Heeeelp!")
class Duck:
def help(self):
print("Quaaaaaack!")
class SomethingElse:
pass
def InTheForest(x):
x.help()
donald = Duck()
john = Person()
who = SomethingElse()
for thing in [donald, john, who]:
try:
InTheForest(thing)
except AttributeError:
print 'Meeowww!'
class Duck(object):
def quack(self):
print "Quack"
class Mallard(object):
def quack(self):
print "Quack Quack"
def shoot(bird):
bird.quack()
for target in [Duck(), Mallard()]:
shoot(target)