# 鸭子类型

鸭子类型是一种编程风格，常见于 Python、Ruby 等动态类型语言中，其判断一个对象是否适合某项操作，依据的是该对象实际拥有的方法和属性，而非其声明的类型或类层次结构。Python 词汇表将其定义为一种风格：不查看对象的类型来确定它是否具有正确的接口；而是直接调用或使用方法或属性，通常配合 `hasattr()` 测试或 EAFP（“请求原谅比请求许可更容易”）编码方式。<sup>[1](https://docs.python.org/3/glossary.html?highlight=eafp)</sup>

| 关键事实 | 详情 |
|---|---|
| 定义 | 对象的适用性取决于它所拥有的方法和属性，而非其正式声明的数据类型<sup>[2](https://kfilin.com/IT/python/_/Christian_Hill_Learning_Scientific_Programming_with_Python_Cambridge.pdf)</sup> |
| 名称起源 | 亚历克斯·马泰利（Alex Martelli）2000 年 7 月 26 日发往 comp.lang.python 的帖子：“不要检查它是不是鸭子：检查它是否叫起来像鸭子、走起来像鸭子”<sup>[3](https://groups.google.com/g/comp.lang.python/c/CCs2oJdyuzc/m/NYjla5HKMOIJ)</sup> |
| 运行时行为 | 解释器在代码执行时尝试调用；若方法存在则继续执行，否则当场报错，此前没有任何检查点<sup>[4](https://pythoncodecrack.com/duck-typing-vs-structural-typing.html)</sup> |
| 静态对应物 | 结构化子类型，Python typing 文档将其描述为鸭子类型的静态等价物，由 PEP 544 规范，自 Python 3.8 起可用<sup>[5](https://typing.python.org/en/latest/reference/protocols.html)</sup><sup> • </sup><sup>[6](https://peps.python.org/pep-0544/)</sup> |
| 相关语言 | Go 通过方法集隐式满足接口；TypeScript 以结构化方式检查类型兼容性<sup>[7](https://go.dev/doc/faq)</sup><sup> • </sup><sup>[8](https://www.typescriptlang.org/docs/handbook/type-compatibility)</sup> |
| 互补工具 | 抽象基类在使用 `hasattr()` 显得笨拙或会导致隐蔽错误的场合（例如涉及魔术方法时）补充鸭子类型<sup>[1](https://docs.python.org/3/glossary.html?highlight=eafp)</sup> |

## 术语起源

这一名称来自谚语“如果它走起来像鸭子，叫起来像鸭子，那它一定就是鸭子”。亚历克斯·马泰利是一位意大利计算机工程师、知名的 Python 贡献者，他在 2000 年 7 月 26 日发往 comp.lang.python 新闻组的消息中使用了这一术语，当时正在讨论构造函数应如何在不使用 C++ 式重载的情况下接受文件名、文件对象或数据库连接。他写道，不应检查一个对象是不是鸭子，而应检查它是否叫起来像鸭子、走起来像鸭子，具体取决于代码究竟需要鸭子般行为的哪个子集。<sup>[3](https://groups.google.com/g/comp.lang.python/c/CCs2oJdyuzc/m/NYjla5HKMOIJ)</sup><sup> • </sup><sup>[9](https://devopedia.org/duck-typing)</sup> Devopedia 称这可能是程序员中最早使用该术语的实例之一。<sup>[9](https://devopedia.org/duck-typing)</sup>

剑桥关于编程语言概念的讲义更精确地表述了这一思想：它依据结构而非名义来判断一个对象是否为鸭子，因此一个拥有足够多所需方法和字段的对象就算作所需的那类事物。<sup>[10](https://www.cl.cam.ac.uk/teaching/2021/ConceptsPL/lectures.pdf)</sup>

## 运行时的工作方式

在鸭子类型下，解释器不会对对象能做什么做出任何预先承诺。它只是在代码执行的那一刻尝试调用方法；若方法存在，执行继续，若不存在，则在该点抛出错误。<sup>[4](https://pythoncodecrack.com/duck-typing-vs-structural-typing.html)</sup> 在 Ruby 中，同样的思想表现为消息分发：当一个对象收到它不理解的消息时，会抛出错误，如何响应的决定是在执行过程中即时做出的。<sup>[11](https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/methods.html)</sup>

**检查行为，而非身份。** Python 词汇表指出，鸭子类型避免使用 `type()` 或 `isinstance()` 进行测试，而通常采用 `hasattr()` 测试或 EAFP 编程，即代码假定所需的属性或键存在，若假定被证明为假则捕获异常。<sup>[1](https://docs.python.org/3/glossary.html?highlight=eafp)</sup> 在 2000 年的原始讨论串中，参与者以文件处理为例说明：代码不必验证参数是否为文件，只需期望一个 `read()` 方法即可，许多标准库模块接受“任何具有类似文件对象的 read 方法的对象”。<sup>[3](https://groups.google.com/g/comp.lang.python/c/CCs2oJdyuzc/m/NYjla5HKMOIJ)</sup>

实际效果是无需共享基类的多态。任何两个类，只要实现了一组签名两两相等的方法，就可以被视为呈现同一组方法，即使这两个类来自两个完全不同的库、没有任何共同约定。<sup>[12](https://groups.google.com/g/comp.lang.python/c/1doimwBQcl0)</sup>

## 静态鸭子类型：协议与结构化子类型

鸭子类型是一种运行时的编程方式，但它有静态对应物。Python 的 typing 文档指出，结构化子类型——依据可对对象执行的操作来判断类型——可视为鸭子类型的静态等价物。<sup>[5](https://typing.python.org/en/latest/reference/protocols.html)</sup> PEP 544 题为“协议：结构化子类型（静态鸭子类型）”，为此规定了协议类；`typing.Protocol` 基类和 `@runtime_checkable` 装饰器在 Python 3.8 中加入。<sup>[6](https://peps.python.org/pep-0544/)</sup><sup> • </sup><sup>[13](https://docs.python.org/3/library/typing.html?highlight=typeguard)</sup>

协议类列出一个兼容对象必须提供的方法和属性。一个类如果以兼容的类型定义了协议的所有成员，就算实现了该协议，完全不需要继承协议；`typing` 模块还定义了一些预置协议，如 `Iterable[T]`，用于鸭子类型常见的场景。<sup>[5](https://typing.python.org/en/latest/reference/protocols.html)</sup> PEP 544 的理由是：像 PEP 484 那样要求类显式标记为支持某个 ABC，与惯用的动态类型 Python 代码风格不符，对于实现被隐藏的库类型尤其困难。<sup>[6](https://peps.python.org/pep-0544/)</sup>

运行时检查仍然有限且需主动启用。默认情况下，`isinstance()` 和 `issubclass()` 对协议类型会失败；用 `@runtime_checkable` 装饰的协议可以配合它们使用，但检查只考察所需方法或属性是否存在，而不考察其类型签名。<sup>[6](https://peps.python.org/pep-0544/)</sup><sup> • </sup><sup>[13](https://docs.python.org/3/library/typing.html?highlight=typeguard)</sup> PEP 544 故意将其设为主动启用，因为当属性可在实例化后动态设置时，实例检查并不完全可靠。<sup>[6](https://peps.python.org/pep-0544/)</sup>

## 其他语言中的鸭子类型与结构化类型

**Go。** Go 类型自动满足任何指定其方法子集的接口，无需 `implements` 声明。Go 常见问题解答将此描述为一种结构化类型，它使实现包与定义接口的包解耦，允许类型同时满足多个接口，并允许事后添加接口而无需标注原始类型。<sup>[7](https://go.dev/doc/faq)</sup> 规则对签名要求严格：方法名和签名必须与接口完全匹配，Go 不会像某些其他类型系统那样提升参数或结果类型。<sup>[14](https://go.dev/doc/faq?source=post_page-----656bc8293b----------------------)</sup>

**TypeScript。** [TypeScript](https://www.edgepedia.org/zh/typescript) 中的类型兼容性基于结构化子类型：若 `y` 至少拥有与 `x` 相同的成员，则 `x` 与 `y` 兼容。文档指出，在 C# 或 Java 等名义类型语言中，当类未显式声明自己实现该接口时，等价的赋值会报错；选择结构化设计是因为 [JavaScript](https://www.edgepedia.org/zh/javascript) 代码广泛使用匿名对象和对象字面量。<sup>[8](https://www.typescriptlang.org/docs/handbook/type-compatibility)</sup>

Python 清晰地展示了这种分离：该语言在其整个历史中一直拥有鸭子类型，却完全没有结构化类型系统，后来 `typing.Protocol` 为外部类型检查器添加了可选的静态结构化检查，而不改变鸭子类型的运行时。<sup>[15](https://rafael.bernard-araujo.com/the-principle-is-not-the-mechanism-isp-dip-and-language-structures-in-practice.php)</sup>

## 权衡与互补机制

鸭子类型的灵活性在可靠性方面是有代价的。如果没有健壮的、路径覆盖充分的单元测试套件，静态系统本可捕获的类型不匹配可能只在运行时才暴露。<sup>[16](https://softwareengineering.stackexchange.com/questions/313224/from-a-software-development-lifecycle-perspective-is-duck-typing-a-benefit-or-a)</sup> 另一方面，无需接口定义，这减少了代码量，并让不相关的类得以协作。<sup>[16](https://softwareengineering.stackexchange.com/questions/313224/from-a-software-development-lifecycle-perspective-is-duck-typing-a-benefit-or-a)</sup><sup> • </sup><sup>[12](https://groups.google.com/g/comp.lang.python/c/1doimwBQcl0)</sup>

Python 提供的机制与鸭子类型并存，而非取代它。抽象基类在使用 `hasattr()` 显得笨拙或会导致隐蔽错误的场合（例如涉及魔术方法时）通过定义接口来补充它，并支持不从 ABC 继承但仍被 `isinstance()` 和 `issubclass()` 识别的虚拟子类。<sup>[1](https://docs.python.org/3/glossary.html?highlight=eafp)</sup> `collections.abc` 中的 ABC 在运行时部分走向结构化检查：一些简单接口通过所需方法的存在与否直接识别，因此定义了 `__iter__` 的类无需注册即可通过 `isinstance(obj, Iterable)`，但复杂接口仍需要注册或子类化，因为接口不仅仅是方法名的存在。<sup>[17](https://docs.python.org/3/library/collections.abc.html)</sup>

研究也将鸭子类型视为静态信息的来源。伦敦[帝国理工学院](https://www.edgepedia.org/zh/imperial-college-london)的一篇博士论文形式化了一种技术，从程序任意一次运行中可证明存在的特征来“冻结”变量的鸭子类型，利用这些特征集来精化 Python 程序流分析的结果。<sup>[18](https://spiral.imperial.ac.uk/entities/publication/e0686cf6-d176-4d9d-a3e2-4cd2c769430f)</sup>

## References

1. [Glossary, Python 3 documentation](https://docs.python.org/3/glossary.html?highlight=eafp)
2. [Glossary, Learning Scientific Programming with Python (Cambridge)](https://kfilin.com/IT/python/_/Christian_Hill_Learning_Scientific_Programming_with_Python_Cambridge.pdf)
3. [Alex Martelli, "polymorphism (was Re: Type checking in python?)", comp.lang.python, July 26, 2000](https://groups.google.com/g/comp.lang.python/c/CCs2oJdyuzc/m/NYjla5HKMOIJ)
4. [Duck Typing vs Structural Typing in Python, PythonCodeCrack](https://pythoncodecrack.com/duck-typing-vs-structural-typing.html)
5. [Protocols and structural subtyping, Python typing documentation](https://typing.python.org/en/latest/reference/protocols.html)
6. [PEP 544 – Protocols: Structural subtyping (static duck typing)](https://peps.python.org/pep-0544/)
7. [Frequently Asked Questions, The Go Programming Language](https://go.dev/doc/faq)
8. [Type Compatibility, TypeScript Documentation](https://www.typescriptlang.org/docs/handbook/type-compatibility)
9. [Duck Typing, Devopedia](https://devopedia.org/duck-typing)
10. [Concepts in Programming Languages, University of Cambridge lecture notes](https://www.cl.cam.ac.uk/teaching/2021/ConceptsPL/lectures.pdf)
11. [Methods, Ruby user's guide](https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/methods.html)
12. ["Missing interfaces in Python...", comp.lang.python, 2006](https://groups.google.com/g/comp.lang.python/c/1doimwBQcl0)
13. [typing – Support for type hints, Python 3 documentation](https://docs.python.org/3/library/typing.html?highlight=typeguard)
14. [Go FAQ (interface satisfaction rules)](https://go.dev/doc/faq?source=post_page-----656bc8293b----------------------)
15. [The Principle Is Not the Mechanism: ISP, DIP, and Language Structures in Practice, Rafael Bernard Araujo](https://rafael.bernard-araujo.com/the-principle-is-not-the-mechanism-isp-dip-and-language-structures-in-practice.php)
16. [From a software development lifecycle perspective, is duck-typing a benefit or a problem?, Software Engineering Stack Exchange](https://softwareengineering.stackexchange.com/questions/313224/from-a-software-development-lifecycle-perspective-is-duck-typing-a-benefit-or-a)
17. [collections.abc – Abstract Base Classes for Containers, Python 3 documentation](https://docs.python.org/3/library/collections.abc.html)
18. [Inferring useful static types for duck typed languages, PhD thesis, Imperial College London](https://spiral.imperial.ac.uk/entities/publication/e0686cf6-d176-4d9d-a3e2-4cd2c769430f)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › 编程语言 › 编程语言概念

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/duck-typing

English original: https://www.edgepedia.org/duck-typing
