Python ABCs: registering vs. subclassing

旧街凉风 提交于 2019-12-03 08:05:01

Registration does not give you the "missing methods" implemented on top of those you define: in fact, registration is non-invasive with respect to the type you're registering -- nothing gets added to it, nothing gets removed, nothing gets altered. It only affects isinstance and issubclass checks: nothing more, nothing less.

Subclassing an ABC can and does give you plenty of methods implemented "for free" by the ABC on top of those you're having to define yourself.

The semantics of an operation that's totally non-invasive like registering, compared to those of an operation that's intended to enrich a class, like subclassing, obviously cannot be identical; so your understanding of "the whole point of the ABCs" is imperfect -- ABCs have two points, one obtained by subclassing ("invasive"), one by registering (non-invasive).

Note that you can always multiply-inherit if you already have a class like your original Mapping: class GoogMapping(Mapping, collections.Mapping): ... will give you the same results as inheriting Mapping directly from collections.Mapping -- a new type with all the auxiliary methods added by collections.Mapping.

Ah, looks like dict() is looking for the keys method... It doesn't use the ABCs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!