Keep the lifespan of variable after multiple function calls?

后端 未结 4 1219
抹茶落季
抹茶落季 2021-01-27 17:18

Assuming:

def myfunc(x):
    my_list  = []
    list.append(x)

is there a keyword to stop a variable(my_list) from being reassigned? Let\'s supp

4条回答
  •  难免孤独
    2021-01-27 17:59

    I believe the behaviour you're seeking is almost exactly how mutable default arguments work in python: instantiated only during function definition.

    def myfunc(x,*args,my_list=[]):
        my_list.append(x)
    

    The *args will protect the list from being overwritten by an erroneously passed second argument.

提交回复
热议问题