HomeToolsAbout

Duck Typing

What is it

"If it walks like a duck, and it quacks like a duck, then it must be a duck"

Concept related to dynamic typing.

Type or the class of an object is less important than the methods it defines.

When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.

class SomeRandomClass: def __len__(self): return 34 some_random_class = SomeRandomClass() len(some_random_class) # 34 my_str = "Hello World" my_list = [34, 54, 65, 78] my_dict = {"one": 123, "two": 456, "three": 789} len(my_str) # 11 len(my_list) # 4 len(my_dict) # 3 my_int = 9 my_float = 1.3 len(my_int) # TypeError: object of type 'int' has no len() len(my_float) # TypeError: object of type 'float' has no len()
AboutContact