Describes the default parameters in Python functions in detail _python

Source: Internet
Author: User
Tags current time datetime function definition function prototype
Import datetime as DT
 
def log_time (message, Time=none):
  If the None:
    time=dt.datetime.now ()
  print ( ' {0}: {1} '. Format (Time.isoformat (), message)

I recently found a nasty bug in a piece of Python code that resulted from the wrong use of default parameters. If you already know everything about the default parameters, just to make fun of my ridiculous mistake, skip to the end of this article. Well, I wrote this code, but I'm pretty sure I was possessed by the demon that day. You know, sometimes that's the way it is.

This article is just a summary of some basic elements of the standard and default parameters of Python functions. Remind you to be aware of pitfalls that may exist in your code. If you're just beginning to touch Python and start writing some functions, I really recommend that you look at the contents of a function in the official Python manual, linked as follows: Defining functions and more on defining functions.
briefly review the function

Python is a powerful object-oriented language that pushes this programming paradigm to the top. However, object-oriented programming still relies on the concept of function, which you can use to process data. Python has a broader concept of callable objects, that is, any object can be invoked, and the invocation means applying data to it.

A function is a callable object in Python, and at first glance it behaves like a function in other languages. They fetch some data, which is called parameters, and then processes them, and then returns the result (none if no return statement is available).

Arguments are declared as placeholders (when defining functions) to represent objects that are actually passed in when the function is called. In Python you don't have to declare the type of the parameter (for example, as you do in C or Java) because Python philosophy relies on polymorphism.

Remember, the python variable is a reference, that is, the memory address of the actual variable. This means that Python functions always work in "address" (here is a C + + term), and when you call a function, instead of copying the value of a parameter to replace the placeholder, point the placeholder to the variable itself. This leads to a very important result: you can change the value of the variable within the function. Here's a good visual explanation on the reference mechanism.

References play a very important role in Python, which is the backbone of Python's full polymorphic approach. For this very important topic, please click on this link to see a better explanation.

To check if you understand this basic feature of the language, follow this simple code (variable ph means "placeholder (placeholder)")

>>> def print_id (ph):
. Print (Hex (ID (ph))
...
>>> A = 5
>>> print (Hex (ID (a))
0x84ab460
>>> print_id (a)
0x84ab460
>>>
>>> def alter_value (ph):
... ph = ph + 1 ... return
ph
... >>> B = Alter_value (a)
>>> b
6
>>> a
5
>>> hex (ID (a))
' 0x84ab460 '
>>> hex (ID (b))
' 0x84ab470 '
>>>
>>> def alter_ Value (ph):
... ph.append (1) ... return
ph
...
>>> a = [1,2,3]
>>> b = Alter_value (a)
>>> a
[1, 2, 3, 1]
>>> b
   [1, 2, 3, 1]
>>> hex (ID (a))
' 0xb701f72c '
>>> hex (ID (b))
' 0xb701f72c '
>>>

If you're not surprised by what's going on here, it means you've mastered one of the most important parts of Python, and you can safely skip the explanations below.

The print_id () function shows that placeholders inside functions are exactly the same as variables passed in at run time (their memory addresses are consistent).

Two versions of Alter_value () are intended to change the values of incoming parameters. As you can see, the first alter_value () does not change the value of variable A as successfully as the second Alter_value (). What is this for? In fact, the behavior of both is the same, trying to modify the value of the incoming original variable, but in Python some variables are immutable (immutable), and integers are in this column. On the other hand, the list is not immutable, so the function is able to complete the work guaranteed by its name. Here you can find a more detailed introduction to immutable types.

There are some things to say about functions in Python, but these are the basics of standard parameters.
Default parameter values

Sometimes you need to define a function to accept a parameter, and when this parameter appears or does not appear, the function behaves differently. If a language does not support this, you have only two choices: the first is to define two different functions, deciding which one to call each time, and the second is that both methods are feasible, but not optimal.

Python, like other languages, supports default parameter values, that is, function arguments can be specified at call time, or you can leave blank to automatically accept a predefined value.

A very simple (and useless) example of a default value is as follows:

def log (Message=none):
  if message:
    print (' log: {0} '. Format (message))

This function can be run with a single parameter (can be none)

 
>>> log ("File closed")
Log:file closed
>>> log (None)
>>>

But you can also run without parameters, which in this case will accept the default value set in a function prototype (none in this case)

>>> log ()
>>>

You can find more interesting examples in the standard library, for example, in the Open () function (see official documentation)

Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)

A function prototype can prove that, for example, a call such as F = open ('/etc/hosts ') hides many parameters (mode, buffering, encoding, etc.) by passing in a default value, and makes the typical application case of this function very simple and easy to use.

As you can see in the built-in open () function, we could use standard or default parameters in a function, but the order in which they appear in a function is fixed: Call the standard arguments first, and then call the default parameters.

Def a_rich_function (A, B, C, D=none, e=0): Pass
  

The reason is obvious: if we can place a default parameter before the standard parameter, the language cannot understand that the default parameter has been initialized. For example, consider the following function definition

Def a_rich_function (A, B, D=none, C, e=0): Pass
  

What parameters are we passing in when calling function A_rich_function (1, 2, 4, 5)? Is it d=4, c=5 or c=4, e=5? Because D has a default value. So the definition of this order is forbidden, and if you do, Python throws a SyntaxError

>>> def a_rich_function (A, B, D=none, C, e=0):
...
 File "<stdin>", line 1
syntaxerror:non-default argument follows default argument
>>>

Default parameter evaluation

The default parameters can be improved by normal values or by function call results, but the latter technique requires a special warning

A normal value is hard-coded, so no value is required except at compile time, but the function call expects the evaluation to be performed at run time. So we can write this.

Import datetime as DT
 
def log_time (message, Time=dt.datetime.now ()):
  print ("{0}: {1}". Format (Time.isoformat (), message))

Every time we call Log_time () We expect it to provide the current time correctly. The tragedy is not successful: the default parameter is evaluated when it is defined (for example, when you first import a module), the result of the call is as follows

>>> log_time ("message 1")
2015-02-10t21:20:32.998647:message 1
>>> log_time ("Message 2")
2015-02-10t21:20:32.998647:message 2
>>> log_time ("Message 3")
2015-02-10t21:20:32.998647: Message 3

If you assign a default value to an instance of a class, the result is even more bizarre, and you can read about it in Hitchhiker ' s Guide to python!. Under.. The usual workaround is to replace the default parameter with none and check the parameter values inside the function.

Conclusions

The default parameter can greatly simplify the API, you need to pay attention to its unique "failure point", that is, the timing of the evaluation. Surprisingly, one of the most basic elements of Python, the parameters and references of functions, is one of the biggest sources of error, sometimes for experienced programmers. I suggest taking time to learn about references and polymorphism.
Related reading:

    • OOP Concepts in Python 2.x–part 2
    • Python 3 OOP part 1–objects and types
    • Digging up Django class-based views–2
    • Python Generators–from iterators to cooperative multitasking–2
    • OOP Concepts in Python 2.x–part 1

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.