Introduced in Python 3.8 via the typing module, Protocols offer a more flexible approach than ABCs, known as structural duck typing, where an object is considered valid if it has certain attributes or methods, regardless of its actual inheritance.
Unlike traditional duck typing, where type compatibility is determined at runtime, structural duck typing allows for type checking at compile time. This means that you can catch type errors before your code even runs (while in your IDE, for example), making your programs more robust and easier to debug.
The key advantage of using Protocols is that they focus on what an object can do, rather than what it is. In other words, if an object walks like a duck and quacks like a duck, it’s a duck, regardless of its actual inheritance hierarchy. This is particularly useful in a dynamically typed language such as Python, where an object’s behavior is more important than its actual type.
For example, you can define a Drawable protocol that requires a draw() method. Any class that implements this method would implicitly satisfy the protocol without having to explicitly inherit from it.
Here’s a quick example to illustrate the concept. Let’s say you need a Protocol named Flyer that requires a fly() method. You can define it as follows:
from typing import Protocol class Flyer(Protocol): def fly(self) -> None: ...
And that’s it! Now, any class that has a fly() method would be considered Flyer, whether it explicitly inherits from the Flyer class or not. This is a powerful feature that allows you to write more generic and reusable code and adheres to the principle of composition over inheritance.
标签:Python,duck,class,Flyer,typing,method,Protocols From: https://www.cnblogs.com/zhangzhihui/p/18361881