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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-08-15 Go - Predeclared identifiers, Keywords, Operators and punctuation