Python is a multi-pattern language, object-oriented programming and structured oriented programming language. Python is developed by Guido Van Rossum in February 1991. The only and only purpose of Python is to code readability which allows programmers to express concepts within fewer lines of code.
Duck typing is a concept which is only related to dynamic typing in
which the type or the class of an object which is less important as compare to
methods while defining. When we use duck typing, we do not check types at all.
But we have to check for the presence of a given method or attribute as
described.
A term which is commonly relates to dynamically typed programming
languages and polymorphism concept. The idea behind using the Duck principle is
that the code itself does not care about whether an object is a duck, but
instead it does only care about whether it quacks.
The
main aim of Duck typing is to design
such a class to know the desired behaviour’s without implementing the protocol,
sub classing, interface, or abstract base classes.
Example -1
class
FruitJuice:
def execute(self):
print('Mango')
print('Apple')
print('Grapes')
print('Chickoo')
class
Juice:
def
code(self, ide):
ide.execute()
ide
= FruitJuice ()
desk = Juice ()
desk.code(ide)
Output:
Mango
Apple
Grapes
Chickoo
In
the above code, we have created a FruitJuice class that has to execute()
method. In the Juice-class, we have passed the ide as an argument
in the code(). An ide is an object of FruitJuice class.
With the help of ide, we called the execute() method of FruitJuice
class.
Example -2
class
Pigeon:
def fly(self):
print("I am a Pigeon and I can
fly.”)
class Eagle:
def fly(self):
print("I am a Eagle and I can
fly.”)
class Dog:
def walk(self):
print("I am a Dog I can walk only
but I can’t fly.”)
def bird_flying(birds):
birds.fly()
We
pass the three animals and ask each of them to fly. While Pigeon and Eagle can
fly, the but Dog cannot fly and therefore throws an error.
fly(Pigeon())
fly
(Eagle ())
fly(Dog())
In
above example fly(Dog()) will throw an error to overcome that problem Duck type
is introduced in Python.
Duck
typing is just a perfect example of dynamic typing in Python which arranges
related functionality over specific data types as per requirement.
At TCCI Coaching Institute we
provide Python development training as per student’s convenience.
For More Information:
Call us @ 9825618292
Visit us @
http://tccicomputercoaching.com
No comments:
Post a Comment