The main function of the role, what does?
1, the modular function program, the function module clear
2, reducing the workload of repeated code
3, easy to read and maintain, and debugging
First, the end of the function and return value
# -*- coding: utf-8 -*-
f1 DEF ():
Print ( "This IS Fun ()")
return # function call ends
Print ( "- End 1--")
Print ( "Print 2")
return "--- End 2 -"
f1()
print(type(f1()))
operation result:
This is Fun()
This is Fun()
<class 'NoneType'>
1. function in the face of the return statement, this time a function call is over
2. The return value of the function is, but here is the type of None
Look at the following example:
def mth_return():
return 1,"String",["a","b"],{"K1":1,"Key2":2}
print(mth_return())
print(type(mth_return()))
operation result:
(1, 'String', ['a', 'b'], {'K1': 1, 'Key2': 2})
<class 'tuple'>
At this time, the return value is a tuple
Second, the parameters of the function
For the function, the variables following the function name commonly known as: parameter, function call, the value will be called an: argument
# -*- coding: utf-8 -*-
def method (name, age): # name, age parameter is a
print (name, age)
DEF method2 (name, Age = "18 is"): # default parameter values providing
print (name, age)
n = "Mr.James"
method(n,38) #n是实参
method2("Zhang")
method2("Mr.Zhang",28)
operation result:
Mr.James 38
Zhang 18
Mr.Zhang 28
Third, the key parameters of the function
For the above example, is a function of position parameters, a position correspondence, no more and no less
The following example is a bit different with the above, call in Python: keyword arguments
# -*- coding: utf-8 -*-
def test(name="James",age=29):
print("name:{},{}".format(name,age))
test(age=20,name="Mr.Zhang")
operation result:
name:Mr.Zhang,20
Fourth, variable length parameters of the function
For the position parameter, parameters, and arguments require one correspondence, if or when the uncertain parameters which need to be able to expand in the future well, Python provides vararg
用法:def function(self,*args,**kwargs)
Specific examples:
Example 1:
# coding = utf-8
def test(name,*args):
print(name)
print(args)
print(args[3])
test ( "Mr.Zhang", 1,2,3, [ "a", "b"], { "Key1": 1, "Key2": 2}) # * args returns a tuple
operation result:
Mr.Zhang
(1, 2, 3, ['a', 'b'], {'Key1': 1, 'Key2': 2})
['a', 'b']
Example 2:
Coding. 8 = UTF-#
DEF test2 (name, args *, ** kwargs): # ** kwargs returns a dictionary
Print (name)
Print (args)
Print (kwargs)
test2("Mr.Zhang",1,2,3,['a','b'],{"Key1":1,"Key2":2},age=18,sex="F")
operation result:
Mr.Zhang
(1, 2, 3, ['a', 'b'], {'Key1': 1, 'Key2': 2})
{'age': 18, 'sex': 'F'}
Nested functions
In the Python programming language, create another function (object because Python everything is an object, the object is actually a function) in the body of the function is perfectly legal, this function is called internal / nested functions.
example:
# coding : utf-8
def outer():
def inner():
print("is Inner Method")
print("Is outer Method")
inner()
# Call the outer function
outer ()
# call the outer () intrinsic functions, error
# inner ()
operation result:
Is outer Method
is Inner Method
When the inner () # call to inner (), there are mistakes
NameError: name 'inner' is not defined
Closure function
What is closure?
If an internal function, the variables in the outer scope (not global scope) is referenced, then the internal function is considered to be closure (closure)
He said the point is clear: Inside the function, reference is made free variables of the outer function
Packages are closed:
Save-shaped body function information, the local variable of the function information can be saved for the installation calculation, hidden is useful
In many GUI or API supports callback event-driven programming is also very useful
There are two ways to call closure:
Called directly internally
Returns the function name
eg
1. Direct call internally
# -*- coding: utf-8 -*-
outer DEF (name):
DEF Inner (name):
# name = "Mr.zhang" where # name value overrides the following function calls the outer argument, which is a function of variables involved in the scope of the range of
print ( "sub method :% S "% name)
# __closuer__ used to determine whether the built-in property is a closure, the return address, is returned None, the closure is not a function
Print (inner .__ closure__)
inner (name) directly inside # call the
outer ( "GuiDo")
operation result:
sub method :GuiDo
(<cell at 0x000001D2792EF7C8: function object at 0x000001D2793687B8>,)
eg
2. Return function name
# -*- coding: utf-8 -*-
def sumer(num = 0):
count = [num]
def add():
count[0] += 1
return count[0]
return add
f = sumer(3)
print(f())
print(f())
print(f())
operation result:
7
8
9