interactive help on the base object

Chris Angelico rosuav at gmail.com
Sun Dec 8 22:17:05 EST 2013


On Mon, Dec 9, 2013 at 2:05 PM, Mark Janssen <dreamingforward at gmail.com> wrote:
> But, in any case, if you don't have a way to map your abstract objects
> into machine types, you're working on magic, not computer science.

Maybe, but that mapping isn't always an inheritance relationship.
Ultimately the computer can't work with my data without it being
represented in memory and in registers (at least in part - "relational
database" could be considered a type, the full implementation of which
is never actually loaded into memory), but the most common way to do
this is effectively some form of composition. For instance, C++ has a
type called "pair" (actually a template); what's the most obvious way
to define the type "pair of integers"? Place the first integer, then
place the second integer. The pair has two members, first and second.
The pair isn't the first integer, nor is it the second integer. It
doesn't make sense to inherit pair from integer, so you don't. You
compose it of two integers.

class Pair(object):
    # in C++, we'd need to declare these:
    # int first;
    # int second;
    def __init__(self, first, second):
        self.first, self.second = first, second

Calling integer methods on a Pair makes no sense. Which of its members
did you want to call that on? Both of them? (Wouldn't make sense if
you had a mixed pair, like pair<employee,gun> which could be a little
awkward to try to fire().) You can't sensibly use a Pair in a context
where an integer would be wanted, so it fails LSP. It composes, but
does not inherit from, int.

ChrisA



More information about the Python-list mailing list