When Python uses list as a function parameter, will the parameter be initialized?

Source: Internet
Author: User
You can see the following code: deffoo (a, B []): B. append (a) printb:

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
The official document explains here: the default args is evaluated only once during definition.
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)...     print b... >>> f(1)[1]>>> f(1)[1]>>> f(1)[1]>>> a = []>>> b = []>>> a.append(1)>>> b[]>>> 
Needless to say, add an id () to output the so-called address of B, and you will understand.

No, def foo (a = []) is written as the default parameter value, which is initialized only once in the function declaration. It will not change later.

Note: We recommend that you 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 also some minor differences between def foo (* args, ** kargs) AND foo (* args, ** kargs. No. The default values are shared and will only be created once. No new object will be created each time. that is to say, using a mutable object as the default value of a function can cause confusion. similarly, if you use a dictionary as the default parameter, a similar result is returned.

def foo(k,v, fdict={}):    fdict[k] = v    print fdictfoo(1,2)foo(3,4)

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.