What's the Python version for “Code against an interface, not an object”?

后端 未结 4 2069
长情又很酷
长情又很酷 2021-01-30 06:45

Inspired by a great question (and bunch of great answers) from here.

Does the statement \"Code against an interface, not an object\" have any significance in Python?

4条回答
  •  猫巷女王i
    2021-01-30 07:29

    To understand interfaces in Python you have to understand duck-typing. From the very Python glossary:

    duck-typing: A programming style which does not look at an object’s type to determine if it has the right interface; instead, the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). (Note, however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs hasattr() tests or EAFP programming.

    Python encourages coding for interfaces, only they are not enforced but by convention. Concepts like iterables, callables or the file interface are very pervasive in Python - as well the builtins that rely on interfaces like map, filter or reduce.

提交回复
热议问题