Define a Measurable Protocol
Advanced · Write the code · from Python Protocols: Duck Typing with Type Safety
From the lesson: Python Protocols: Duck Typing with Type Safety
Python has a famous saying: "If it walks like a duck and quacks like a duck, then it's a duck." This is called duck typing - you don't care what an object is, only what it can do. But duck typing has a downside: your editor and type checker have no idea what you expect.
Read the lessonCreate a Measurable Protocol class that requires a length() method returning an int. Then create a Playlist class with a songs list attribute and a length() method that returns the number of songs. Finally, write a function print_length(item) that takes a Measurable and prints its length.
Call print_length with a Playlist containing ['Song A', 'Song B', 'Song C'].
More Protocol exercises
All Python exercises · 50 practice problems · Advanced Python quiz