An "Object" class?

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Aug 31 03:07:42 EDT 2019


Cristian Cocos wrote:
> And that is because entities belonging to the same
> taxonomical class ("clade") have common features, and also inherit the
> features of the taxonomical parent.

I think the notion you're after is what is known in the Python
world as a "protocol". This is an informal collection of methods
and behaviours that an object can conform to, which makes it
usable in certain ways. Some fundamental ones include the
sequence protocol, the mapping protocol, and the iterator
protocol.

I'm not aware of a diagram, but the "Built-In Types" section
of the Library Reference describes all the major protocols and
lists the types that belong to them.

Originally these protocols did not have any formal embodiment.
Nowadays Python has ABCs (Abstract Base Classes) which provides
a way to formalise them. You may also find it instructive to
look at the docs for the collections.abc module.

Note that ABCs a bit weird, because you can register a class as
belonging to an ABC, so that isinstance() and issubclass() will
behave as though the class inherits from the ABC even though
it doesn't. For example,

 >>> import collections.abc
 >>> issubclass(list, collections.abc.Sequence)
True
 >>> list.__mro__
(<class 'list'>, <class 'object'>)

Unfortunately this means there is no easy way to find all the
ABCs that a given class is a member of, so you'll have to rely
on documentation to build the taxonomy that you're after.

Also, there is no requirement for a class implementing a given
protocol to be registered with a corresponding ABC. Most of the
built-in ones are, but there are plenty of classes out in the wild
that aren't. So there isn't any foolproof way for a program to ask
an object a question like "are you a sequence".

-- 
Greg



More information about the Python-list mailing list