2011년 독서 목록
python tip - default parameter mutation
Default parameter values are evaluated when the function definition is executed.This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to useNoneas the default, and explicitly test for it in the body of the function, e.g.: defwhats_on_the_telly(penguin=None):ifpenguinisNone:penguin=[]penguin.append(“property of the zoo”)returnpenguin
- 2011/08/03 15:37 에 작성