1.

What do you mean by duck typing? How does Python implement duck typing?

Answer»

Duck typing is a special case of dynamic polymorphism and a characteristic found in all dynamically typed languages including Python. The premise of duck typing is a famous quote: "If it walks like a duck and it QUACKS like a duck, then it must be a duck".

In programming, the above duck test is used to determine if an object can be used for a particular purpose. With statically typed languages, suitability is determined by an object's type. In duck typing, an object's suitability is determined by the presence of certain METHODS and properties, RATHER than the type of the object itself. Here, the idea is that it doesn't actually matter what type data is - just whether or not it is possible to perform a certain operation.  

Take a simple case of ADDITION operation. Normally addition of similar objects is allowed, for example the addition of numbers or strings. In Python, addition of two integers, x+y actually does int.__add__(x+y) under the hood.

>>> x=10 >>> y=20 >>> x+y 30 >>> int.__add__(x,y) 30

Hence, addition operation can be done on any objects whose class supports __add__() method. Python’s data model describes protocols of data types. For example sequence protocol stipulates that any class that supports iterator, len() and __getitem__() methods is a sequence. 

The simple example of duck typing given below demonstrates how any object may be used in any context, up until it is used in a way that it does not support:

class Duck:     def fly(self):         print("Duck flies") class Airplane:     def fly(self):         print("Airplane flies") class Kangaroo:     def swim(self):         print("Kangaroo runs") d=Duck() a=Airplane() k=Kangaroo() for b in [d,a,k]:    b.fly() output: Duck flies Airplane flies Traceback (most recent call last):   File "example.py", line 18, in <module>     b.fly() AttributeError: 'Kangaroo' object has no attribute 'fly'

Duck typing is possible in certain statically typed languages by providing extra type annotations  that instruct the compiler to arrange for type checking of classes to occur at run-time rather than COMPILE time, and include run-time type checking code in the compiled output.



Discussion

No Comment Found