an oop question

Julieta Shem jshem at yaxenu.org
Fri Nov 4 20:58:19 EDT 2022


Greg Ewing <greg.ewing at canterbury.ac.nz> writes:

> On 4/11/22 1:29 am, Julieta Shem wrote:
>> Perhaps I can reduce the
>> class Pair to just being a pair as we know it, made of two things, then
>> we create a class called Sequence, which is really a composition of
>> Pairs, comes with a length method and we derive Stack from it.
>
> That sounds better. But be careful -- a Sequence class would
> probably be expected to have methods for e.g. inserting and
> removing things in the middle, which you might not want to
> allow for a Stack.

I guess we could override those and raise NotImplementedError?

I don't actually know how to do that.  Say I have those two classes
Empty and Pair.  Here's a way to design Seq:

class Seq:
  class SeqEmpty(Empty):
    pass
  class SeqPair(Pair):
    def insert(self):
      return ...
    def remove(self):
      return ...
  def __new__(clss, *args):
    if len(args) == 0:
      return Seq.SeqEmpty()
    else:
      return Seq.SeqPair(*args)

How do I override insert in Stack?

class Stack(Seq):
  def insert(self):
    raise NotImplementedError
   
That doesn't work because when I create an object of type Stack, it is
actually an object of type Seq.SeqEmpty or of type Seq.SeqPair.  So it
seems that Stack should inherit Seq.SeqPair or Seq.SeqEmpty and these
unions begin to look like a lot of typing.


More information about the Python-list mailing list