17. python custom functions, 17. python Functions

Source: Internet
Author: User

17. python custom functions, 17. python Functions

What is a function? To put it bluntly, a series of codes are encapsulated to realize code reuse.

What is code reuse?

Suppose I have the following requirements:

Custom Functions

  After knowing what the function is for, we will start to learn the user-defined function, that is, to create this magic machine.

Sample Code:

Def dfb (a): ''' a series of operations ''' return 'a bowl of % s rice' % aa = dfb ('meters ')
B = dfb ('meters ') print
Print B

 

In this way, we get two bowls of rice, which is really convenient and fast.

Now let's explain what is in it:

1. def is a keyword of python and is specially used to customize functions.

2. dfb is a function name for future calls.

3. a In (a) Is the function parameter and provides data for operations in the function.

4. return is used to return an object. This object can be the processing result of the function, or the processing status of the function.

1. def

There is nothing to explain.

 

2. Function Name

The function name is similar to the variable name.

For example, if I write a function but do not call it, what will happen.

Def dfb (a): ''' a series of operations ''' return 'a bowl of % s rice' %

 

There is no output, does it mean that the function does not exist?

Let's see if there is any in the memory:

print id(dfb)

 

Obviously, the function can be found in the memory.

Therefore, when we define a function, python will load the function into the memory, but when it is not called, the internal code of the function will not be executed.

Obviously, it is similar to the principle of variable assignment, so pay attention to one problem:If the function name conflicts with the variable name, the value is assigned again. Python explains the variable name from top to bottom, that is, who occupies the variable name under it. The remaining one can only wait for garbage collection in the memory.

Def dfb (a): ''' a series of operations ''' return 'a bowl of % s rice' % adfb = 1 print dfb

 

  

print dfb()

 

  

So what are the requirements for function name naming?

Function names must be more strict than variable names. In addition to complying with the requirements of variable names,Cannot Use numbers.

Therefore, function names can only use letters and underscores (_), while avoiding the python keywords.

In addition, in the pep8 standard, function names are recommendedLowercase.

2. Functions Act on Domains

  A major difficulty in parameter functions, many people do not understand what the so-called form parameters and real parameters are.

To understand the differences, we must first explainFunction ScopeWhat is going on.

This is the so-called function scope.

When python executes the code in the function, it is placed in a new environment, and this new environment is like a virtual machine installed on a computer. There are no previously created objects in the new environment, which is the same as I cannot find my local files in the virtual machine.

After the function is run, python will destroy the runtime environment of the function, that is, the virtual machine will be deleted after the task is completed, and the data in it will be deleted. But the code is still valid. For example, I registered an account on a website on a virtual machine. After registration, I deleted the virtual machine. However, my registered account will not be deleted, but my browsing history on the virtual machine is gone.

Here is a question I asked:

A = 123def dfb (a): ''' a series of operations ''' return 'a bowl of % s rice' % AB = 'mi' print dfb (B)

What will the function output?

Because the function has a scope, although the global variable a exists, the function is executed in the new environment, so there is no such variable. When the execution of the function is complete, the execution environment will be destroyed and will not affect each other. Naturally, the direction of a is not changed.

It is precisely because the execution of a in the function disappears, so it is formal and has no significance for the whole world. Therefore, the parameter is used only for internal processing of the function. When we call a function, the actual parameter, such as the actual parameter B in dfb (B), is called a real parameter.

  The variables in the function are local variables, while the external variables are global variables..So the variables defined in the function, that is, local variables, are only valid within the function.

 2. global

What if I want to force the declaration of global variables in the function?

A = 123def dfb (a): ''' a series of operations ''' B = 1 return 'a bowl of % s rice' % adfb ('mi') print B

 

  

You can use the global keyword:

A = 123def dfb (): ''' a series of operations ''' global B # I declare that I want to create a global variable B = 1 # Then I assign a value to B and return a bowl of % s rice '% adfb ('meters ') print B

 

In this way, you can create global variables in the function.

Now, if you have the opportunity to ask, will the global variables declared inside the function be assigned a new value in conflict with the previous ones?

Answer: Yes.

But pay attention to one problem:

A = 123def dfb (a): ''' a series of operations ''' global a # When I declare global variable a and want to overwrite the previous values, return 'a bowl of % s rice '% AB = 'mi' print dfb (B)

 

However, an error is reported:

  We cannot declare formal parameters as global.

Let's change the name of the formal parameter:

A = 123def dfb (c): ''' a series of operations ''' global a # I declare the global variable, to overwrite the previous value of a = c return 'a bowl of % s rice' % AB = 'mi' dfb (B) print

Yes. Our idea is correct. Declaring a global variable in the function will indeed overwrite the existing variable.

 

 

3. Passing Parameters

Passing parameters is another important and difficult point of the function.

Parameters are passed to make the function more suitable. In the above example, we write a function with parameters in the column. Do you mean that the function must be a parameter?

Def test (): print 'However, I do not have the parameter 'test ()

 

It can be seen that there is no parameter, but when there is no parameter, no matter how the call results are the same, the flexibility is too low, so in order to improve flexibility, there is a need for parameters.

Parameters are classified into common parameters, default parameters, and dynamic parameters.

1. Common Parameters

def test(a,b,c):    print a    print b    print ctest(1,2,3)

 

It can be seen that the parameters are passed in order, which is called a common function.

However, there is a problem:

def test(a,b,c):    print a    print b    print ctest(1,2)

 

Three parameters are required, but only two parameters are required. In this case, an error is returned. But I don't want to do this. I hope that when I do not pass the parameter, the parameter has a default value. In this case, the default parameter is required.

 

2. Default Parameters

def test(a,b,c=3):    print a    print b    print ctest(1,2)

 

Passing the parameter is equivalent to assigning the value of the real parameter to the form parameter. If you give the parameter, I will execute a = 1, B = 2 in order, but now c has been assigned 3 values, so even if you do not pass the parameter, the number of parameters is enough.

Of course, you can also pass enough parameters. text (, 3) is equivalent to re-assigning values to c.In this way, you can process the passed parameters based on the passed parameters, and process the parameters based on the default values if they are not passed..

Therefore, we can set the default values for all parameters.

However, this situation may occur:

def test(a=1,b,c=3):    print a    print b    print ctest(1,2)

 

This statement is not allowed, because it is difficult to process parameters without default values, so when the default parameters and common parameters exist at the same time, put the common parameters first:

def test(b,a=1,c=3):    print a    print b    print ctest(1,2)

 

The reason for this writing is that we need to use the parameter passing method: We can explicitly specify which value is passed to which parameter:

def test(b,a=1,c=3):    print a    print b    print ctest(a=1,b=2,c=3)

 

If this parameter is explicitly transmitted, the sequence of parameter passing is arbitrary. That is, text (a = 1, c = 3, B = 2) is also acceptable. The final value assignment result is the same.

However, when using common parameters and explicitly passing parameters, You must place the default passing parameters at the beginning: text (2, a = 1, c = 3 ,) generally, it can be explicitly transmitted in sequence. This means that when writing a function, we need to put all common parameters in front and the default parameters in the back to correspond to them.

 

3. Dynamic Parameters

Because our function may not only be used by ourselves at the end, but is called by users or others, but others may not know how many parameters I accept here.

If the parameter is missing, we can use the default parameter to solve the problem. However, if the parameter is missing, an error will be reported and the user experience will be poor. To improve the function adaptability, dynamic parameters are displayed.

def test(a,*args,**kwargs):    print atest(1,2,c=3)

 

In this way, the adaptability of functions is higher, so what are the meanings of * args and ** kwargs here.

Let's first look at the type:

def test(a,*args,**kwargs):    print type(args),type(kwargs)test(1,2,c=3)

 

They are the original and dictionary. Here, note that the "*" in front only indicates the type of the file. "*" indicates the ancestor, "*" indicates the dictionary, and the real variable name is. It is not specified that args should be used to name the ancestor and kwargs to name the dictionary. But this is a standard way to let other programmers see at a glance what it is.

Next, let's take a look at what is stored in it:

def test(a,*args,**kwargs):   print args   print kwargstest(1,2,c=3)

 

  It stores the default parameter-based multi-pass value in a ancestor, and uses its parameter name key for explicit parameter-based multi-pass. The parameter value is a value and forms a dictionary.

You can ignore them, or you can process them, assign values, cycles, or judge members.

4. return

When a function encounters a return statement, it indicates that the function execution is complete. An object is returned and the execution environment of the function is destroyed.

However, you can see the following statement in the above example:

Def test (): print 'I did not write return' test ()

 

It is found that no return statement can still be executed. During the call, something is output and the execution stops after it is executed again.

Note,When no return statement is written in the function, the default return object is an empty object.. That is, even if no data is written, python also handles it internally.

At this time, some people cannot tell the difference between the output and return values of the function.

In this case, operations such as print in a function can output content because the code is effective even though the execution environment of the function is independent. External operations can also be performed inside the function. However, not all functions have such obvious output results after execution. At this point, we need to check whether the function is successful, or if I put the meter in, after you perform this operation, you always need to take out the meal for me.

This is the meaning of return in the function.Returns an object.. This object can be a description of the execution status or a result after processing.

Def test (): '''a series of operations '''return 'deal with 'test ()

 

But I still don't see anything.

  That's because although the function returns an object, the object is still in the memory, and you haven't taken it out. Of course, nothing can be seen.

print test()

 

In this way, you can assign values to variables, for example, a = test (), and then call variable. Of course, True and False are used to return results, which indicates success and failure, and can be used with the conditional control statement.

Def test (): ''' a series of operations ''' print test ()

Of course, if this parameter is not specified, null object None is returned by default.

 

def test(a,b):    c = a + b    return cprint test(1,2)

 

It is also possible to return the processed results. It depends on your needs.

 

Finally, although return indicates that the function is over, it means that there is only one return in a function.

Def test (a, B): if! = 0: return a + B return 'a cannot be 0' print test)

 

The Conditional Control statement can be used to return different objects in different situations, so that the function can process more cases.

 

Anonymous functions:

In some cases, I only want to use a function to process very simple services. Writing a complete function will increase the amount of code. In this case, I can use an anonymous function for processing.

Python uses lambda to create anonymous functions:

1. lambda is just an expression. The function is much simpler than def.

2. The body of lambda is an expression rather than a code block. Only limited logic can be encapsulated in lambda expressions.

3. lambda functions have their own namespaces and cannot access parameters outside their own parameter lists or in global namespaces.

4. Although lambda functions seem to be able to write only one row, they are not equivalent to C or C ++ inline functions. The latter aims to call small functions without occupying the stack memory, thus increasing the running efficiency.

 

Syntax:

lambda [arg1 [,arg2,.....argn]]:expression

 

Example:

# Writable function description sum = lambda arg1, arg2: arg1 + arg2 # Call the sum function print "after the sum value is:", sum (10, 20) print "the sum value is:", sum (20, 20)

 

Although it is an anonymous function, it still needs to be assigned to a variable, otherwise it cannot be called. The variables in anonymous functions are also local variables, which are no different from the complete functions.

Anonymous functions are recommended to be used only when processing simple functions. If it is too complicated, use the complete functions.

Pass statement

  Python pass is a null statement to maintain the integrity of the program structure. Pass does not do anything. It is generally used as a placeholder statement.

Def test (): pass # I want to use this function to handle some things, but I have no idea how to write it now.

 

  Of course, not only functions can be used, but also process control.

If a <= 10: passelse: print 'a greater than 10'

 

In other words, it only plays a placeholder role.

 

Let's talk about user-defined functions first. Any errors and modifications will be made later.

 

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.