π‘ Idea: Duck typing is a computer science concept where the type of an object is largely ignored—only the methods the object defines matter. This is sometimes referred to as dynamic typing because the type of an object is determined dynamically at runtime rather than checked by the compiler. Instead of checking the type, the programming language (e.g., Python) simply attempts to run the methods as specified in the code. If it works, great, if not it raises an error.
Duck Typing Defined
This method is used to provide assistance for dynamic typing in Python.
With dynamic typing, you do not need to stipulate the variable data type.
You are able to use different data type principles to the same variable later in the code.
For example, in the below code snippet, you assign an int
, a list, and a string to variable x.
x = 14 print(int(x)) x = [100, 200, 300, 400] print(list(x)) x = 'Duck' print(str(x))
When you run the code, you see the Python interpreter returns the results without an error. This is a result of dynamic typing.
Output:
14 [100, 200, 300, 400] Duck
Programming languages such as Java will require you to announce a variable and note its data type.
Duck Typing Example
You see in this sample Duck typing is giving the code a try, and if it comes across an unknown it attempts to solve it anyway.
In the below code treat it as a duck if it can swim, and has wings if not try something else.
class Duck: def swim(self): print("I'm a duck, and I can swim.") def Wings(self): print("I'm a duck, and I can fly.") class deer: def swim(self): print("I'm a deer, and I can swim, but I can not fly.") for animal in [Duck(), Deer()]: animal.swim() animal.wings()
When you run the code, the duck can swim and fly. The deer can swim but can not fly, and we get an attribute error that the object deer
does not have wings.
Output:
I'm a duck, and I can swim. I'm a duck, and I can fly. I'm a deer, and I can swim, but I can not fly. Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 13, in <module> animal.wings() AttributeError: 'deer' object has no attribute 'wings'