Comparing Duck Typing in Python's Built-in Types
00:00 Exploring Duck Typing in Python’s Built-in Types. Duck typing keeps Python flexible by focusing on what an object can do instead of needing strict types.
00:11
Also, built-in types share common behaviors like iteration, sorting, and reversing, making them straightforward to use in for
loops and other operations.
00:21 Now, what does this mean? It means that you can take advantage of duck typing when you’re dealing with built-in types.
00:29 Let’s go and play around with the built-in types a little. Take iteration, for example. Do you think all built-in types support iteration?
00:39
Look at this code snippet. You have a bunch of examples to test this idea. A list, a tuple, a string, a dictionary, and a set. And then you’re putting everything in a list called collections
, and you’re trying to print them in a nested for
loop. Or in other words, you’re testing if they support iteration.
00:57 What do you think will happen if you run this code? Would it run without any problems, or would you get an error? You can pause this video for a little and think about it.
01:09
Okay, ready? When you run the code, it works. No errors. You get every single item inside of the stuff inside your collections
list, like the list, the string, and the set printed.
01:22 This means that all of the built-in types you have here support iteration. How can you connect this conclusion with what you already know about duck typing?
01:31 Tell us in the comment section below.
01:36 Now, here’s a table that breaks down which built-in Python types, like lists, tuples, strings, support different operations. You can see that some, like lists, can do almost everything, while others, like sets, don’t support indexing or slicing because they’re unordered.
01:53 This is a great example of how Python focuses on what an object can do rather than what it is. If something supports an operation, you can use it no matter the type.
02:05 Now, here’s a challenge for you. Try creating a class that checks whether a built-in type supports each operation from the table in the last slide. Configure it however you prefer, and when you’re done, show off your solution in the comment section below.
Become a Member to join the conversation.