On Mon, 31 Oct 2022 at 09:05, Julieta Shem <js...@yaxenu.org> wrote:
>
> Julieta Shem <js...@yaxenu.org> writes:
>
> [...]
>
> >>   . If you should, however, be talking about the new "type hints":
> >>   These are static and have "Union", for example, "Union[int, str]"
> >>   or "int | str".
> >
> > I ended up locating such features of the language in the documentation,
> > but I actually am not interested in declaring the type to the compiler
> > (or to the reader).
> >
> > I was looking for a solution like yours --- thank you! ---, although I
> > was hoping for handling that situation in the construction of the Stack
> > object, which was probably why I did not find a way out.  Right now I'm
> > looking into __new__() to see if it can somehow produce one type or
> > another type of object depending on how the user has invoked the class
> > object.
> >
> > Terminology.  By ``invoking the class object'' I mean expressions such
> > as Class1() or Class2().  ``Class1'' represents the object that
> > represents the class 1.  Since the syntax is that of procedure
> > invokation, I say ``invoking the class object''.
>
> An experiment.  What's my definition of Stack?  It's either Empty or
> Pair, so it's a union.  So let us create two inner classes (that is,
> inner to Stack) and make them behave just like Empty and Pair.  Using
> __new__(), we can produce a Stack object that is sometimes Empty() and
> sometimes Pair(...).
>

The most straight-forward way to represent this concept in an
object-oriented way is subclassing.

class Stack:
    ... # put whatever code is common here

class Empty(Stack):
    ... # put Empty-specific code here, possibly overriding Stack methods

class Pair(Stack):
   ... # ditto, overriding or augmenting as needed

This way, everything is an instance of Stack, but they are still
distinct types for when you need to distinguish.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to