程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python -- functions

編輯:Python

Catalog

The function classification

Function definition and call

Formal parameters and actual parameters

docstring

Return value

Functions are also objects

Scope of variable ( Global and local variables )

Local variable and global variable efficiency test

Parameter passing

Pass a reference to a mutable object

Pass a reference to an immutable object

Shallow copy and deep copy

Several types of parameters

          Positional arguments

          Default parameter

          Named parameters

          Variable parameters

Force named parameters

lambda Expressions and anonymous functions

eval() function

Recursive function

Nested function ( Internal function )

nonlocal And global

LEGB The rules


The function classification

Python Functions in are divided into the following categories :

        1. Built in functions We used it earlier str()、list()、len() These are built-in functions , We can use it directly .

        2. Standard library functions We can go through import Statement import library , Then use the function defined in it

        3. Third party library functions Python The community also provides a lot of high-quality Libraries . After downloading and installing these libraries , through import The statement leads to Enter into , You can then use the functions of these third-party libraries

        4. User defined functions User defined functions , Obviously, it is also a function defined to meet the needs of users in development . What we learn today is Is how to customize functions .

Function definition and call

        Python in , The syntax for defining a function is as follows :
 

def Function name ([ parameter list ]) : 
    ''' docstring '''
The body of the function / Several sentences 

The main points of :

1. We use def To define a function , Then there is a space and the function name ;

        (1) Python perform def when , Will create a function object , And bound to the function name variable .

2. parameter list

        (1) In parentheses is a list of formal parameters , Multiple parameters are separated by commas

        (2) Formal parameters do not need to declare types , There is no need to specify the return value type of the function

        (3) No parameter , Empty parentheses must also be left

        (4) The argument list must correspond to the formal parameter list one by one

3. return Return value

        (1) If the function body contains return sentence , Ends the function execution and returns the value ;

        (2) If the function body does not contain return sentence , Then return to None value . 

4. Before calling the function , You must first define the function , That is, call first def Create function objects

        (1) Built in function objects are created automatically

        (2) Standard library and third-party library functions , adopt import When importing a module , Will execute... In the module def sentence

Formal parameters and actual parameters

        Don't go into details

docstring

        That is, the comment of the function

Return value

return Key points of return value :

        1. If the function body contains return sentence , Ends the function execution and returns the value ;

        2. If the function body does not contain return sentence , Then return to None value .

        3. To return multiple return values , Use list 、 Tuples 、 Dictionaries 、 The collection will multiple values “ Save up ” that will do

Functions are also objects

Scope of variable ( Global and local variables )

Global variables :

        1. Variables declared outside function and class definitions . The scope is the defined module , Start from the defined location until the module end .

        2. Global variables reduce the generality and readability of functions . The use of global variables should be avoided as much as possible .

        3. Global variables are generally used as constants .

        4. Function to change the value of the global variable , Use global Make a statement

local variable :

        1. In the body of a function ( Contains formal parameters ) Declared variables .

        2. References to local variables are faster than global variables , Priority use .

        3. If the local variable has the same name as the global variable , Then hide the global variable in the function , Use only local variables with the same name

a = 100 # Global variables
def f1():
global a # If you want to change the value of a global variable within a function , increase global Keyword declaration
print(a) # Print global variables a Value
a = 300
f1()
print(a)
100
300
a = 100
def f1():
a = 3
print(a)
f1()
print(a)
3
100

Local variable and global variable efficiency test

         The query and access speed of local variables is faster than that of global variables , Priority use , Especially in cycles . In places with special emphasis on efficiency or where there are many cycles , You can improve the running speed by turning global variables into local variables .

Parameter passing

The parameter passing of a function is essentially : Assignment operation from argument to formal parameter . 

        Python in “ Everything is the object ”, All assignment operations are “ Assignment of references ”. therefore ,Python The parameters in are passed as “ reference ”, No yes “ Value passed ”. The specific operations are divided into two categories :

        1. Yes “ The variable object ” Conduct “ Write operations ”, Act directly on the original object itself .

        2. Yes “ Immutable object ” Conduct “ Write operations ”, Will produce a new “ Object space ”, And fill this space with new values .

The variable object Yes : Dictionaries 、 list 、 aggregate 、 Custom objects, etc

Immutable object Yes : Numbers 、 character string 、 Tuples 、function etc.

Pass a reference to a mutable object

         The parameters passed are mutable objects ( for example : list 、 Dictionaries 、 Other custom variable objects, etc ), The actual transmission is still right The reference of image . No new object copy is created in the function body , Instead, you can directly modify the passed object .

b = [10,20]
def f2(m):
print("m:",id(m))
m.append(30)
f2(b)
print("b:",id(b))
print(b)
m: 45765960
m: 45765960
[10,20,30]

Pass a reference to an immutable object

         The passed parameter is an immutable object ( for example :int、float、 character string 、 Tuples 、 Boolean value ), The actual transmission is still right The reference of image . stay ” Assignment operation ” when , Because the immutable object cannot be modified , The system will create a new object .

a = 100
def f1(n):
print("n:",id(n))
n = n+200
print("n:",id(n))
print(n)
f1(a)
print("a:",id(a))
n: 1663816464
n: 46608592
300
a: 1663816464

         obviously , adopt id We can see n and a Start with the same object . to n After the assignment ,n Is a new object .

Shallow copy and deep copy

         Shallow copy : Don't copy the contents of the shell object , Just copy the reference of the child object .

         Deep copy : It will copy all the memory of the child object , Changes to child objects do not affect the source object

​
import copy
def testCopy():
''' Test shallow copy '''
a = [10, 20, [5, 6]]
b = copy.copy(a)
print("a", a)
print("b", b)
b.append(30)
b[2].append(7)
print(" Shallow copy ......")
print("a", a)
print("b", b)
def testDeepCopy():
''' Test deep copy '''
a = [10, 20, [5, 6]]
b = copy.deepcopy(a)
print("a", a)
print("b", b)
b.append(30)
b[2].append(7)
print(" Deep copy ......")
print("a", a)
print("b", b)
testCopy()
print("*************")
testDeepCopy()
a [10, 20, [5, 6]]
b [10, 20, [5, 6]]
Shallow copy ......
a [10, 20, [5, 6, 7]]
b [10, 20, [5, 6, 7], 30]
************
a [10, 20, [5, 6]]
b [10, 20, [5, 6]]
Deep copy ......
a [10, 20, [5, 6]]
b [10, 20, [5, 6, 7], 30]
​

Several types of parameters

        Positional arguments

When a function is called , Arguments are passed in positional order by default , The number and formal parameters need to match .

def f1(a,b,c):
print(a,b,c)
f1(2,3,4)
f1(2,3) # Report errors , Positional parameters do not match 

        Default parameter

We can set default values for some parameters , So these parameters are optional when passed .

def f1(a,b,c=10,d=20): # The default value parameter must be after the normal position parameter
print(a,b,c,d)
f1(8,9)
f1(8,9,19)
f1(8,9,19,29)
8 9 10 20
8 9 19 20
8 9 19 29

        Named parameters

We can also pass parameters according to the name of the formal parameter

def f1(a,b,c):
print(a,b,c)
f1(8,9,19) # Positional arguments
f1(c=10,a=20,b=30) # Named parameters
8 9 19
20 30 10

        Variable parameters

Variable parameters refer to “ Variable number of parameters ”. There are two situations :

1. *param( An asterisk ), Collect multiple parameters into one “ Tuples ” In the object .

2. **param( Two asterisks ), Collect multiple parameters into one “ Dictionaries ” In the object .

def f1(a,b,*c):
print(a,b,c)
f1(8,9,19,20)
def f2(a,b,**c):
print(a,b,c)
f2(8,9,name="giaohu",age=18)
def f3(a,*b,**c):
print(a,b,c)
f3(8,9,10,name="giaohu",age=18)
8 9 (19,20)
8 9 {'name': 'giaohu', 'age': 18}
8 (9, 10) {'name': 'giaohu', 'age': 18}

 

         Force named parameters

In the asterisk “ Variable parameters ” Add new parameters later , It must be called “ Force named parameters ”.

def f1(*a,b,c):
print(a,b,c)
f1(2,3,4) # Will report a mistake . because a It's a variable parameter , take 2,3,4 Collect all . cause b and c No assignment .
f1(2,b=3,c=4)
(2,) 3 4

lambda Expressions and anonymous functions

        lambda Expressions can be used to declare anonymous functions .lambda Function is a simple 、 Define the function... On the same line Methods .

f = lambda a,b,c:a+b+c
print(f(2,3,4))
g = [lambda a:a*2,lambda b:b*3,lambda c:c*4]
print(g[0](6),g[1](7),g[2](8))
9
12 21 32

eval() function

         The string str Evaluate as a valid expression and return the result .

s = "print('abcde')"
eval(s)
a = 10
b = 20
c = eval("a+b")
print(c)
30

Recursive function

        The realization of Fibonacci series :

def f(n):
if n==1 or n==2:return 1
else:return f(n-1)+f(n-2)
for i in range(1,11):
print(f(i),end=" ")
1 1 2 3 5 8 13 21 34 55

Nested function ( Internal function )

def f1():
print('f1 running...')
def f2():
print('f2 running...')
f2()
f1()
f1 running...
f2 running..

nonlocal And global

        nonlocal Local variables used to declare the outer layer .

        global Used to declare global variables .

a = 100
def outer():
b = 10
def inner():
nonlocal b # Declare a local variable of an external function
print("inner b:",b)
b = 20
global a # Declare global variables
a = 1000
inner()
print("outer b:",b)
outer()
print("a:",a)
inner b: 10
outer b: 20
a: 1000

LEGB The rules

        In short , From the inside out

 

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved