Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

duck typing in python

# 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.
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #duck #typing #python
ADD COMMENT
Topic
Name
4+1 =