an oop question
Julieta Shem
jshem at yaxenu.org
Sun Oct 30 10:54:24 EDT 2022
ram at zedat.fu-berlin.de (Stefan Ram) writes:
> Julieta Shem <jshem at yaxenu.org> writes:
>>My desire seems to imply that I need a union-like data structure.
>
> You only need to worry about such things in languages with
> static typing. For example, to have a function that can
> sometimes return an int value and at other times a string
> value in C, one would need a union.
>
> In Python with its dynamic typing, one does not need unions.
>
> def an_int_sometimes_and_sometimes_a_string( x ):
> if x:
> return 2
> else:
> return "two"
Nice. This means that I can solve my stack-union problem by writing a
procedure --- say stack(...) --- that sometimes gives me Empty() and
sometimes gives me Stack().
>>> stack()
Empty()
>>> stack(1,2,3,4)
Stack(4, Stack(3, Stack(2, Stack(1, Empty()))))
The user interface of this non-empty case is that we're stacking up the
arguments, hence the number 1 ends up at the bottom of the stack.
def stack(*args):
if len(args) == 0:
return Empty()
else:
return Stack(args[-1], stack(*args[:-1]))
I realize now that I'm using the same solution of the /open()/
procedure. Depending on the arguments, open() produces a different type
of object.
> . 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''.
More information about the Python-list
mailing list