Comparisons and sorting of a numeric class....

Chris Angelico rosuav at gmail.com
Mon Jan 12 23:35:43 CET 2015


On Tue, Jan 13, 2015 at 9:27 AM, Andrew Robinson
<andrew3 at r3dsolutions.com> wrote:
> Huh? I'm not adding any values when I merely subclass bool ; and even if the
> subclass could be instantiated -- that's doesn't mean a new value or
> instance of the base class (bool) must exist.  For I could happily work with
> a new subclass that contains no new data, but only an already existing
> instance of 'True' or 'False' as its value source.   That means there is no
> new value...  but at most (and even that could be worked around) a new
> instance of a subclass containing an existing instance of it's base class.

If you subclass bool and instantiate your subclass, you have made a
new instance of bool, because every instance of a subclass is an
instance of its superclass. The Python bool type has the following
invariant, for any object x:

assert not isinstance(x, bool) or x is True or x is False

(You can fiddle with this in Py2 by rebinding the names True and
False, but you could replace those names with (1==1) and (1==0) if you
want to be completely safe. Likewise, the name "bool" could be
replaced with (1==1).__class__ to avoid any stupidities there. But
conceptually, that's the invariant.)

Subclassing bool breaks this invariant, unless you never instantiate
the subclass, in which case it's completely useless.

ChrisA



More information about the Python-list mailing list