an oop question

Weatherby,Gerard gweatherby at uchc.edu
Tue Nov 1 16:32:33 EDT 2022


I think:

class Stack:
    def __init__( self, *args ):
        self.data = args

    def __str__( self ):
        return f"Stack({','.join(str(x) for x in self.data)})"

gives equivalent output for the if len(args) is 0 or 2, if it’s okay for self.data to be a tuple.

class Stack:
    def __init__( self, *args ):
        self.data = list(args)

    def __str__( self ):
        return f"Stack({','.join(str(x) for x in self.data)})"

If it’s desired self.data be a list.


From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of Stefan Ram <ram at zedat.fu-berlin.de>
Date: Tuesday, November 1, 2022 at 3:43 PM
To: python-list at python.org <python-list at python.org>
Subject: Re: an oop question
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

Julieta Shem <jshem at yaxenu.org> writes:
>clarify.  If I wish for an empty stack, I wish I could just say
>>>> Stack()
>Stack()
>and if I wish for a nonempty stack, I'd write
>>>> Stack(1, Stack(2, Stack(3, Stack())))
>Stack(1, Stack(2, Stack(3, Stack())))

  If this is all,

  main.py

class Stack:
    def __init__( self, *args ):
        self.data = [ args[ 0 ], args[ 1 ]]if len( args ) else []
    def __str__( self ):
        if len( self.data ):
            return f"Stack({self.data[0]}, {self.data[1]})"
        else:
            return f"Stack()"

print( Stack() )

print( Stack(1, Stack(2, Stack(3, Stack()))) )

  output

Stack()
Stack(1, Stack(2, Stack(3, Stack())))

  .


--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!itEYnwU5jJ0z8_rkW_q_ogw3ZJUNdHdMNkMLpSAqBdozBNrr7NqPs_gNsbx8W9uXRLZpG38C9an17Yx2zUf-mSA$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!itEYnwU5jJ0z8_rkW_q_ogw3ZJUNdHdMNkMLpSAqBdozBNrr7NqPs_gNsbx8W9uXRLZpG38C9an17Yx2zUf-mSA$>


More information about the Python-list mailing list