[Python] Why is this optional method argument shared across different Python objects?...

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo


    What is the explanation for this?

    class Strange(object):
    def mutate(self, x=[]):
    x.append(1)
    return x

    obj = Strange()
    print obj.mutate()
    another_obj = Strange()
    print another_obj.mutate()

    >> [1]
    >> [1, 1]


    mutate() is called without the optional parameter. Shouldn't x then always be []? What confuses me also is that the value of x is also shared across different objects...

    Continue reading...

Compartilhe esta Página