The default parameters in Python are detailed

Source: Internet
Author: User
Tags cos function definition range sin in python

This article mainly introduces the default parameters in Python, this article explains the rationale of the default parameters, how to correctly use variable parameters and so on, the need for friends can refer to the

The subject of the article

Do not use mutable objects as default parameters for functions such as List,dict, because DEF is an executable statement that evaluates the value of the default default parameter only when DEF executes, so using the default parameter causes the function to execute with the same object all the time, causing the bug.

Basic principle

In the Python source, we use DEF to define functions or methods. In other languages, something like this is often just one by one syntax declaration keywords, but def is an executable instruction. Python code executes by using compile to compile it into pycodeobject.

Pycodeobject is essentially still a static source code, but is stored in bytecode mode because it is oriented to a virtual machine. So code is concerned with how to execute these bytecode, such as stack space size, a variety of constant variable symbol list, and bytecode and source line number of the corresponding relationship and so on.

Pyfunctionobject is produced during the running period. It provides a dynamic environment to associate Pycodeobject with the running environment. Also provides a series of contextual properties for function calls, such as the module in which it is, the global namespace, the default value of the parameter, and so on. This is the work done when the DEF statement is executed.

Pyfunctionobject makes functions logical, not just virtual machines. The combination of Pyfunctionobject and pycodeobject is a complete function.

The following translation of an article, there are some good examples. However, due to the limited level, some do not translate or some translation errors, please understand. If you have any questions please send an email to Acmerfight circle gmail.com, thank you.

Main reference books: "Deep Python Programming" Daniel: Shell and Topsky

Python's handling of default parameters in a function can often be confusing to novice (but usually only once).

When you use a "mutable" object as a default parameter in a function, this can often cause problems. Because in this case the parameter can be modified without creating a new object, such as List Dict.

The code is as follows:

>>> def function (data=[]):

... data.append (1)

... return data

...

>>> function ()

[1]

>>> function ()

[1, 1]

>>> function ()

[1, 1, 1]

As you can see, the list is getting longer. If you look at this list carefully. You will find that the list is always the same object.

The code is as follows:

>>> ID (function ())

12516768

>>> ID (function ())

12516768

>>> ID (function ())

12516768

The reason is simple: every time a function is called, the function always uses the same list object. The changes caused by this use are very "sticky".

Why is this happening?

The default parameter is evaluated only when the "DEF" statement that contains the default parameter is executed. Please see the document description

Https://docs.python.org/2/reference/compound_stmts.html#function-definitions

which has the following paragraph

"Default parameter values are evaluated when the ' function definition is executed. This means so the expression is evaluated once, when the ' function is ' defined, and 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:i f The function modifies the object (e.g. by appending of the item to a list), the default value was in effect modified. This isn't generally not what was intended. A way around this are to use None as the default, and explicitly test for it in the ' function,e.g.:

The code is as follows:

def whats_on_the_telly (Penguin=none):

If Penguin is None:

Penguin = []

Penguin.append ("Property of the Zoo")

Return Penguin

"

"Def" is an executable statement in Python in which the default parameters are computed in the statement context of "Def". If you execute a "def" statement multiple times, it will create a new function object each time. Next we'll see an example.

What do you want to replace it with?

As others have mentioned, replace the default values that can be modified with a placeholder. None

The code is as follows:

def myfunc (Value=none):

If value is None:

Value = []

# Modify Value here

If you want to handle any type of object, you can use the Sentinel

The code is as follows:

Sentinel = Object ()

def myfunc (Value=sentinel):

If value is Sentinel:

Value = Expression

# use/modify Value here

In older code, written before "object" was introduced, you sometimes see

The code is as follows:

Sentinel = [' placeholder ']

The translator notes: Too much water, really do not know how to translate. I'm going to say my understanding sometimes logically you may need to pass a none, and your default value may not be none, and it's just a list that doesn't

Can be written in the default value position, so you need a placeholder, but with none, you don't know if it's the caller who passed it.

Using variable parameters correctly

The last thing to note is that some advanced Python code often takes advantage of this mechanism; For example, if you create a button on a UI in a loop, you might try this:

The code is as follows:

For I in range (10):

DEF callback ():

Print "clicked Button", I

Ui. Button ("button%s"% i, callback)

But you find that callback prints the same number (probably 9 in this case). The reason is that Python's nested scopes are only binding variables, not binding values, so callback only sees the last value of the variable I binding. To avoid this situation, use display bindings.

The code is as follows:

For I in range (10):

DEF callback (I=i):

Print "clicked Button", I

Ui. Button ("button%s"% i, callback)

I=i binds the callback parameter I (a local variable) to the value of the current external I variable. (Translator Note: If you don't understand this example, see Http://stackoverflow.com/questions/233673/lexical-closures-in-python)

Additional two uses local caches/memoization

The code is as follows:

def calculate (A, B, C, memo={}):

Try

Value = Memo[a, B, c] # return already calculated value

Except Keyerror:

Value = Heavy_calculation (A, B, c)

Memo[a, b, c] = value # Update the memo Dictionary

return value

(Useful for some recursive algorithms)

For highly optimized code, a local variable is used to bind the global variable:

The code is as follows:

Import Math

def this_one_must_be_fast (x, Sin=math.sin, Cos=math.cos):

...

How does this work?

When Python executes a def statement, it creates a new function object using what is already ready (including the function's code object and the context property of the function). At the same time, the default parameter values of the function are computed.

Different components can be used like the properties of a function object. The ' function ' used above

The code is as follows:

>>> Function.func_name

' function '

>>> Function.func_code

", Line 1>

>>> Function.func_defaults

([1, 1, 1],)

>>> function.func_globals

{' function ': ,

' __builtins__ ': ,

' __name__ ': ' __main__ ', ' __doc__ ': None}

So you can access the default parameters, you can even modify it.

The code is as follows:

>>> function.func_defaults[0][:] = []

>>> function ()

[1]

>>> Function.func_defaults

([1],)

However, I do not recommend that you use it normally.

Another way to reset the default parameter is to rerun the same DEF statement, and Python will create a new function object with the code object, compute the default parameters, and assign the newly created function object to the same variable as the last. But again, you can do this only if you know exactly what you're doing.

And yes, if you happen to have the pieces but not the function, you can use the function class in the new module to C Reate your own function object.

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.