Will the parameters be initialized when Python uses list as a function parameter?

Source: Internet
Author: User
See this section of code:

def foo (A, b=[]):    b.append (a)    print B

Reply content:

>>>  def  foo   ( bar  =  []):       ...  return  bar  >>>  foo   func_name   ' foo '  >>>  foo   func_defaults   ([],)  >>>  foo   ()  is  foo   func_defaults  [ 0  ]  true   
Official documents are explained here: Default args is evaluated at the time of definition, only once
4. More Control Flow Tools

But......
>>> def f(a, b=[]):...     b.append(a)...     print b... >>> f(1)[1]>>> f(1)[1, 1]>>> def f(a, b=None):...     b = b if b is not None else []...     b.append(a)...     
Don't say anything, add an ID () output B's so-called address, you understand

No, def foo (a=[]) This function parameter is called the default value of the parameter, only once the function declaration is initialized. And then it won't change any more.

Note, it is recommended to know the difference between Def foo (a=[]) and foo (a=[]): The former is the default value of the parameter, and the latter is the keyword arguments. There are subtle differences between this def foo (*args, **kargs) and this foo (*args, **kargs). No, the default values are shared, created only once, and do not create a new object every time. This means that using a Mutable object as the default value of a function can cause confusion in the function. Similarly, using a dictionary as the default parameter results in a similar return.
deffoo(k,v,fdict={}):    fdict[k]=v    printfdictfoo(1,2)foo(3,4)
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.