コンテンツにスキップ

ダックタイピングの使い方: 簡単に理解する方法

[

Duck Typing

Duck typing is a concept in Python related to dynamic typing, where the type or class of an object is less important than the methods it defines. Instead of checking types, duck typing checks for the presence of a given method or attribute. This allows you to call functions or perform operations on different types of objects as long as they define the necessary methods.

For example, in Python, you can call the len() function on any object that defines a .__len__() method. Here’s an example:

class TheHobbit:
def __len__(self):
return 95022
the_hobbit = TheHobbit()
len(the_hobbit) # Output: 95022

In the above code, the TheHobbit class defines a .__len__() method which returns the length of the book. When we create an instance of TheHobbit and call len(the_hobbit), it returns the value 95022.

Duck typing allows you to call the len() function on different types of objects, such as strings, lists, dictionaries, or custom-defined classes like TheHobbit, as long as they define the .__len__() method.

my_str = "Hello World"
my_list = [34, 54, 65, 78]
my_dict = {"one": 123, "two": 456, "three": 789}
len(my_str) # Output: 11
len(my_list) # Output: 4
len(my_dict) # Output: 3
len(the_hobbit) # Output: 95022

However, if you try to call the len() function on objects that do not define the .__len__() method, you will encounter a TypeError.

my_int = 7
my_float = 42.3
len(my_int) # Raises TypeError
len(my_float) # Raises TypeError

In the above code, calling len() on my_int or my_float raises a TypeError because these objects do not define a .__len__() method.

In summary, duck typing allows you to perform operations on objects based on the presence of certain methods or attributes, rather than their specific type or class. It provides flexibility and makes code more reusable.