Python15_ function

Acquaintance function

Understanding function: In a complete project, certain functions will be repeated use, it will function as a function of the package, when we want to use direct call function can be

Essence: a package of a function

advantage:

  1. Simplify the code structure, increasing the degree of multiplexing codes

  2. If you want to modify some of the functions or debug, only you need to modify the corresponding function can be

Defined Functions

#格式:
def 函数名(参数列表):
    语句
    return 表达式

Function name: follow the rules for identifiers

List of parameters (parameter 1, parameter 2, 3 ...... parameter, the parameter n): the caller information to the function, any incoming parameters (variables) must be placed in parentheses, separated by commas

(): Beginning and end of the argument list

Statement: function package features

return: the end of the function, and return information to the caller of the function

Expression: To return to the caller's information

Note: The final return expression can not write

def myPrint():
    print("sunck is a good man!")

No reference No return value function

def myPrint():
    print("sunck is a good man!")

Call functions

Format: function name (parameter list)

The nature of the function call: the argument to a procedure parameter assignment

Containing reference function

Needs, write a function to a string and a function of age, print it out inside the function

def myPrint(str, age):
   print(str,age)
   

Arguments (actual parameters): transfer function to the data of the function call, the value essentially

Parameter (formal parameters): defining a function parentheses variables, the variables essentially

Process is actually parameter passing arguments to a procedure parameter assignment

Parameters must be delivered in order, correspond to the number of the current situation

Return value of the function containing

Requirements: to two logarithmic function, which returns two numbers and

def add(num1, num2):
   return num1 + num2
   
res = add(1,3)
print(res)

Passing parameters

  • classification
    1. Value transfer: transmitting the immutable type, such tuple, string, number
    2. Pass a reference: the type of variable transmission, such as list, set, dict
#值传递
def func1(num):
   num = 10   
temp = 20
func1(temp)
print(temp)

#引用传递
def func2(myList):
   myList[0] = 100
   
list1 = [1,2,3,4,5]
func2(list1)
print(list1)

Note: For most development languages, the basic data types of variables are present stack area, there is heap object type, there is a constant area constant, there is a snippet of code

For the constant stored in the constant region, the variable is stored in the address data, if the same two variables, the data points to the same constant area, so that if () to print two variables with id address, the same results

a = 10
b = 10
print(id(a),id(b))  #输出结果相同

Keyword arguments

Parameter allows the function call order is not the same when defined, python interpreter to match with the matching parameters Parameter Name

  • Whether to display the specified parameters, to facilitate their reading for the purpose of a
def myPrint(str,age):
    print(str,age)

myPrint(age=18,str="sunck is a good man")

The default parameters

The concept: the function is called, if no parameter, the default parameters

** If you use the default parameters into the best default parameters will last

def myPrint(str="sunck is a good man", age = 18)
    print(str,age)
    
myPrint()

def myPrint2(str, age = 18):
    print(str,age)
    
myPrint2("sunck is a good man")

Variable-length parameters

def: can handle more than the defined parameters

In the form of a

def func(name, *arr):   #arr可以为任意符合规范的标识符
    print(name)
    for x in arr:
        print(x)

* Plus an asterisk (*) variables to store all variable parameters unnamed, if no parameter is specified in the function call, it is an empty tuple

def mySum(*arr):
    sum = 0
    for x in arr:
        sum += x
    return sum

print(1,2,3,5,6)

In the form of two

It must be passed as a keyword argument

** represents the key parameters of the dictionary, and represent similar meaning *

def func2(**kwargs):    #kwargs为字典
    print(kwargs)
    print(type(kwargs))
func2(x=1,y=2)

summary

def f(*t):
	print(t)
f(*(1,2,3,4))	# *在此处相当于拆包,在形式参数位置相当于打包,**类似

def ff(**kw):
	print(kw)
ff(**{"name":"aodongbiao","age":23})

You can accept any parameter

def func3(*args, **kwargs):
    pass

Anonymous function

The concept: do not use a statement such as def defined functions, using lambda to create an anonymous function that returns the resulting value is expressed

  • Features:
  1. lambda is just an expression, is simpler than the function body def
  2. The body is a lambda expression, rather than a code block can only be encapsulated only simple logical lambda expressions
    3.lambda function has its own namespace, and can not be accessed outside the free list or parameters in the global namespace parameter
  3. Although lambda is an expression, but looks can only write a single line, but with C and C ++ inline functions inside different

Format: lambda parameter 1, parameter 2 ......, the parameter n: epxreesion

#求两个数的和
sum = lambda num1,num2:num1+num2

print(sum(1,2))


stus=[{"name":"zhangsan","age":23,"sex":"male"},
      {"name":"lisi","age":12,"sex":"femaile"}
]
print("排序前:",stus)
# 根据年龄排序
res=sorted(stus,key=lambda  x:x["age"])
#x:将stus中的元素挨个传给lambda函数,将其中单个元素的整体传给x,x["age"]即字典中的age的值。再把age的值作为参数用于比较
print("排序后:",res)

#动态输入函数
#coding=utf-8
def test(a,b,func):
	return func(a,b)
func = input("please input a function:")	#这是python2中的写法,如果是python3中,func = evla(input("please input a function:"))	#eval即可将输入的语句转为python2中的形式
#假设输入了:lambda x,y:x+y
print(11,22,func)
#则test函数可以计算两个数的和

Turn outside the chapter

  • The import

Format: from modename import name1, name2

  • “_”

If for temporary variables inside the loop and the loop body is not used in the inside, you can use "_", tells the reader that temporary variable has not been used in a loop inside the body

for _ in range(10):
    pass

  • The function complements

Function may be seen as a data type

def sum(a,b):
	return a+b
f = sum
print(f(1,2))
  • The scope and closure
  1. python, the scope of a variable as a function of time units
  2. When the global variable modified, indicating the use of global variables is the outermost
  3. When nonlocal modified instructions nesting level is a variable, i.e., non-local variables
  4. If you do not use nonlocal keyword or global, the internal functions can not be accessed but can not modify the amount of external use of keywords can be changed

Closure
in which a function is also defined a function, and this function uses outside variables. Then this function and use of outside variables inside collectively referred to as closure. Closure is essentially nested function, the function returns the address of the outer layer of the inner function.

def test(number):
	def test_in():
		print(number+100)
	return test_in
ret = test(100)	#返回test_in,并将test_in里面的number用100替换
ret()	#输出200
#ps:也可以给test在定义时添加形参,则在ret调用时必须进行传参。
  • Closure Application and Comments
def test(a,b):
	def test_in(x):
		print(a*x + b)
	return test_in

line1 = test(1,1)	#令line1指向test_in的空间,此时test_in里面用的a是1,b是1
line1(0)
line2 = test(10,4)	#如果发现没有指向test_in的引用,则直接将原来空间里面的a、b进行修改。但是此时有引用指向test_in,就重新开辟一块空间,将原来的test拷贝进去,但是将a赋值为10,b赋值为4,然后将这里面的test_in返回给line2
line2(0)

The recursive
def: function calls itself
when writing recursive or loop, first consider the general export (end condition) problem

The higher-order functions

def: Returns the value of the parameter or a function whose function is a function

def handle(func, *param):
    return func(*param)

def my_sum(*param):
    sum = 0
    for i in param:
        sum += i
    return  sum

print(handle(my_sum,1,2,3,4,5))

The nature of the function

For the function, the function body is actually stored in a space, and the function name (without parentheses) pointing to the space.
So the function name can be regarded as a common variable, assignment and other operations. In other languages (such as C, C ++), the function pointer must be carried out by.

Guess you like

Origin blog.csdn.net/qq_34873298/article/details/89600209