0

The following code seems to append ['next'] twice to the self.list_of, even though its acting on two independent objects.

class Higher:
    def __init__(self, list_of: list = ['item1', 'item2'],):

        self.list_of=list_of

        self.list_of += ['next']


class NumberOne(Higher):

    def __init__(self,**kwargs):

        super().__init__(**kwargs)


class NumberTwo(Higher):

    def __init__(self,**kwargs):

        super().__init__(**kwargs)


if __name__=="__main__":

    n = NumberOne()

    m = NumberTwo()

    print(m.list_of)

I would expect print(m.list_of) to return ['item1', 'item2', 'next'], instead of ['item1', 'item2', 'next', 'next']

I'm not sure whats causing this, can probably find a work around, but would rather understand whats going on.

  • Two independent objects whose `list_of` attributes both reference the *same* list. – chepner Nov 25 '21 at 16:52
  • 1
    You need to be careful with mutable default arguments. [See Also](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). This is causing the surprising effect In your code that: `m.list_of is n.list_of` – Mark Nov 25 '21 at 16:54
  • ok so my options are a) use a copy OR b) use a tuple and convert to a list in each sub – granddejeuner Nov 25 '21 at 17:10

0 Answers0