콘텐츠로 건너뛰기

덕 타이핑(duck typing)의 사용 방법

[

##duck typing ###Duck Typing in Python Duck typing is a concept related to dynamic typing in Python, where the type or class of an object is less important than the methods it defines. Instead of checking types, duck typing focuses on checking for the presence of specific methods or attributes.

For example, in Python, you can call the len() function on any object that defines a .__len__() method. This means that as long as an object has a method that returns the length of the object, it can be used with the len() function.

Here is an example demonstrating duck typing in Python:

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

In this example, we define a class TheHobbit with a __len__() method that returns the word count of the book “The Hobbit”. We then create an instance of this class called the_hobbit and use the len() function on it, which successfully returns the length of the book.

We also demonstrate using the len() function on other objects such as strings, lists, and dictionaries, which all have a __len__() method defined. As long as the object has this method, we can use len() on it.

However, if we try to use len() on objects that do not have a __len__() method, such as integers or floats, we will get a TypeError.

##Conclusion Duck typing allows us to focus on the behavior of objects rather than their types. By checking for the presence of certain methods or attributes, we can use objects interchangeably as long as they satisfy the necessary requirements.

This flexibility makes Python a versatile programming language, allowing developers to write code that can work with a wide range of objects, regardless of their types.

In the next tutorial, we will explore type hinting in Python, which provides a way to specify the expected types of variables and function arguments, helping with code readability and maintainability.