Why the “mutable default argument fix” syntax is so ugly, asks python newbie

前端 未结 8 652
悲&欢浪女
悲&欢浪女 2020-11-30 09:00

Now following my series of \"python newbie questions\" and based on another question.

Prerogative

Go to http://python.net/~goodger/projects/pyco

8条回答
  •  旧巷少年郎
    2020-11-30 09:26

    This is called the 'mutable defaults trap'. See: http://www.ferg.org/projects/python_gotchas.html#contents_item_6

    Basically, a_list is initialized when the program is first interpreted, not each time you call the function (as you might expect from other languages). So you're not getting a new list each time you call the function, but you're reusing the same one.

    I guess the answer to the question is that if you want to append something to a list, just do it, don't create a function to do it.

    This:

    >>> my_list = []
    >>> my_list.append(1)
    

    Is clearer and easier to read than:

    >>> my_list = my_append(1)
    

    In the practical case, if you needed this sort of behavior, you would probably create your own class which has methods to manage it's internal list.

提交回复
热议问题