Wednesday 24 July 2024

What is duck type in python?

Duck typing in Python is a concept related to dynamic typing, where the type or class of an object is less important than the methods it defines or the way it behaves. The name comes from the phrase "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." In programming, this means that if an object implements the necessary methods and behaves in the required way, it can be used in place of any other object that meets those same criteria, regardless of its actual class.



Example of Duck Typing

 

Suppose you have a function that takes an object and calls its `quack` method:

 

```python

class Duck:

    def quack(self):

        print("Quack!")

 

class Person:

    def quack(self):

        print("I'm quacking like a duck!")

 

def make_it_quack(thing):

    thing.quack()

 

d = Duck()

p = Person()

 

make_it_quack(d)  # Output: Quack!

make_it_quack(p)  # Output: I'm quacking like a duck!

```

 

In this example, both `Duck` and `Person` classes have a `quack` method. The `make_it_quack` function calls the `quack` method on the passed object without caring whether it's an instance of `Duck` or `Person`. As long as the object has a `quack` method, the function will work correctly. This is duck typing in action.

 

 Key Points of Duck Typing

 

  1. **Behavior Over Type**: Focus is on what an object can do rather than what it is.
  2. **Flexibility**: Allows for more flexible and reusable code.
  3. **Loose Coupling**: Reduces dependencies on specific classes, making code easier to maintain and extend.

 

Duck typing is a powerful feature in Python that promotes writing more generic and flexible code. However, it also requires careful design and testing to ensure that the objects used in a given context do indeed support the necessary behavior.

TCCI Computer classes provide the best training in online computer courses through different learning methods/media located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.

For More Information:                   

Call us @ +91 98256 18292

Visit us @ http://tccicomputercoaching.com/

No comments:

Post a Comment