Python: Why isn't my default arguments used when calling the method without declaring their values -


this question has answer here:

i thought had learn python , parameters/arguments (which correct term?) local variables within method , if not declared in method call take defined default values. example shows i'm wrong:

this code

def example(foo=[]):     print foo     bar = 'hello world'     foo.append(bar)     return foo  print example() print example() 

prints out this

[] ['hello world'] ['hello world'] ['hello world', 'hello world'] 

i have expected print out:

[] ['hello world'] [] ['hello world'] 

why doesn't happen _?


i know

print example([]) print example([]) 

prints expect. kinda miss point of having default values..

bonus info: using python 2.7.3 , ipython

default values arguments created once per method, @ time of definition, not use, causes trouble (or @ least not entirely straight forward behaviour) mutable values.

to expect, you'll have create inside function instead, like;

def example(foo=none):     if foo none: foo = []     print foo     bar = 'hello world'     foo.append(bar)     return foo 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -