ダックタイピングの使い方: 簡単に理解する方法
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:
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.
However, if you try to call the len()
function on objects that do not define the .__len__()
method, you will encounter a 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.