Python function basics

Source: Internet
Author: User

Why should there be a function? What's wrong with no function?

1, organizational structure is not clear, poor readability

2. Code Redundancy

3, the scalability of poor

Second, the classification of functions:

1, built-in functions: The Python interpreter has been defined for our function is the built-in function, we can use it without prior definition

2, custom functions: We ourselves according to the needs, in advance to customize our own functions to achieve a certain function, if you encounter the same situation can be directly called

Three, three forms of the definition function

The first: The parameterless function (the scenario just performs some action)

def foo (): Print (' from foo ')

The second kind: The parameter function (need to be passed in according to the external parameters, to execute the corresponding logic)

The parameter function is divided into formal parameters and actual parameters.

Formal parameters include:

1. Position parameter: Required parameters

def foo (name,age,sex): print (name) print (age) print (sex)

2. Default function: The parameter is assigned a value when it is defined

The arguments contain:

1. Keyword argument: an argument defined in the form of Key=value

2, positional parameters: according to the location of the parameter value

Foo (' Jim ', ' Male ')

There is also a variable-length parameter: The variable-length parameter refers to the number of arguments, the argument is nothing more than the positional argument and the key argument two

The parameters are handled by the arguments that are defined by the position overflow condition: *

def foo (X,y,*args): #* Assigning the positional arguments to args, args= (3, 4, 5) print (x) print (y) print (args) foo (1,2,3,4,5)


Parameters are handled by arguments that are defined by the keyword overflow condition: * *

def foo (X,y,**awargs): #** assigns positional arguments to Awargs, awargs={' z ': 3, ' E ': 4} print (x) print (y) print (Awargs) foo ( x=1,y=2,z=3,e=4)

Finally, the named keyword parameter: * After the parameter defined, must be passed the value (except for the default value), and must be passed as a keyword argument

def foo (X,y,*args,a=1,**kwargs): print (x, y) #处理传的参数后结果是1 2 print (args) #处理传的参数后结果是 (3, 4, 5) Print (a) #处理传的参数后结果是1 print (Kwargs) #处理传的参数后结果是 {' C ': 4, ' d ': 5}foo (1,2,3,4,5,c=4,d=5)

The third type: Empty functions (Design code structure)

Four, function call

1. return value of function

Return value does not have a type limit

1. No return: Return none, equivalent to return none

2. Return a value: Returns the value

3. Return multiple values: Returns multiple values in the form of tuples

2. Three forms of function call

1. Statement form

2. Form of expression

3, as a parameter of another function

def foo (x, y): if X>=y:return x Else:return yfoo (#语句形式res =foo) *10 #表达式形式, the result of the fetch is done in the expression Res2=foo (foo, 3) #函数调用可以当做另外一个函数的参数print (Res2)


V. Namespaces and Scopes

1. Loading order of namespaces

#1, the Python interpreter starts first, so it first loads: built-in namespaces

#2, execute the *.py file, and then load the global namespace on file basis

#3, if a function is called during the execution of a file, the local namespace is generated temporarily

2. Lookup Order of namespaces

Local namespace---> Global namespaces---> Built-in namespaces

3. Scope

A scope relationship is fixed at the function definition stage, regardless of where the function is called

X=1def num (): x=2 print (x) #x的值为2 x=3num ()


Six, closed packet function

1. Closure function: An intrinsic function contains a reference to an outer scope rather than a global scope

2, the meaning of the closure function

The returned function object, not just a function object, also wraps a layer of scope outside the function, which allows the function to take precedence over the scope of its outer envelope wherever it is called

Import requestsdef outter (URL): # url = ' https://www.baidu.com ' def get (): Response=requests.get (URL) if Response.status_code = =: #取状态码是200的 print (len (response.text)) return Getbaidu=outter (' Https://www.baidu.com ') Baidu ()


Seven, decorative device

1, the principle of follow

Open closure principle: Closed to modification, open to expansion

1. Do not modify the source code of the object being decorated

2. Do not modify the calling method of the decorated object

2. Simulate the time of opening a webpage

Import Timedef Index (): Time.sleep (3) print (' Hello ') def inner (): Start=time.time () #开始的 Time index () stop=time.time () #网页打开后的时间 print (Stop-start) inner ()


The above implementation of our needs, but the inner function contains the index function, can only count the execution time of index, not conducive to the reuse of code, so to improve

Import Timedef Index (): Time.sleep (3) print (' Hello ') def timmer (func): Def inner (): Start=time.time () Func () Stop=time.time () print (Stop-start) return Innerindex=timmer (index) #index不是以前的index, is renamed, so When you call the index function on a user, the operation does not change index ()

Final version

Import Timedef Timmer (func): Def wrapper (*args,**kwargs): Start_time=time.time () Res=func (*args,**kwargs) Stop_time=time.time () print (' Run time is%s '% (stop_time-start_time)) return res return wrapper@t Immerdef foo (): Time.sleep (1) print (' from foo ') foo ()

Execution process: When the program executes, the empty function defines the stage, executes @timmer, jumps to the Timmer function, executes to return wrapper------> @timmer------->foo ()-----> Execute wrapper function---> Execute foo ()




Python function basics

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.