current position:Home>Python notes (IV): use of functions and modules

Python notes (IV): use of functions and modules

2022-01-30 10:44:00 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

Function function

Master programmer Martin Fowler Sir once said :“ Code has a lot of bad taste , Repetition is the worst ! ”.

Duplicate functions can be encapsulated in a system called “ function ” In the function module of , To achieve oneness , Or code snippets associated with functions .

Defined function

The rules for defining functions are as follows :

  • Function code block to def Key words start with , Followed by the function name and parentheses () .
  • The naming rules of function names are consistent with those of variables
  • return Keyword is used to exit the function , Optionally return an expression... To the caller .

The syntax is shown below :

def  Function name ( parameter list ):
     The body of the function 
    return sentence 
 Copy code 
#  Define a function   Put two parameters inside 
def sum(arg1, arg2):
    #  return 2 The sum of parameters ."
    total = arg1 + arg2
    return total


#  call sum function 
sumNum = sum(10, 20)
print(sumNum) // 30
 Copy code 

The parameters of the function

In addition to basic operations such as defining functions and calling functions , You can also use arguments in functions . The parameters of a function are simply variables that can be used in the body of the function . Unlike variables , The of such a variable is passed in before the function body .

The default value of the parameter

When you call a function , If no parameters are passed , Then the default parameters .

def printInfo(name, age=12):
    " Print any incoming strings "
    print(" name : ", name)
    print(" Age : ", age)
    return


#  call a function 
printInfo(age=10, name=" Xiaohong ")
print("------------------------")
printInfo(name=" Xiao Ming ")
 Copy code 

Variable parameters

The so-called variable parameter refers to when calling a function , You can pass... To the function 0 One or any number of parameters .

#  Use the asterisk expression to express stamp You can receive 0 One or any number of parameters 
def printInfo(*stamp):

    #  Variable parameters can be placed in for Take the value of each parameter from the loop 
    for i in stamp:
        print(i)
    return


printInfo(" A bowl week ")
printInfo(1, 2, 3, 4, 5, 6, 7)
printInfo("hello", "hi")
 Copy code 

Use modules to manage functions

In the same .py If two function names in the file are the same , because Python There is no concept of function overloading , Then the later definition will overwrite the previous one , This means that only one function with the same name exists . This is the time modular The function of .

Python Each file in represents a module (module), There can be functions with the same name in different modules , When using a function, you can use import Keyword is introduced into the specified module to distinguish each function .

example : Define two modules , Respectively module1 and module2, Then test the introduction process

module1

def printinfo():
    print(" This is the of the first module printinfo function ")
 Copy code 

module2

def printinfo():
    print(" This is the of the second module printinfo function ")
 Copy code 
  1. Use import Keywords are introduced directly
import module1
import module2
#  Add... Through the module name . Function name is used to introduce 
module1.printinfo()
module2.printinfo()
 Copy code 
  1. Use import...as Keyword rename
import module1 as m1
import module2 as m2
#  You can add... By renaming the name . Function name is used to introduce 
m1.printinfo()
m2.printinfo()
 Copy code 
  1. Use from...import...as Keyword renaming introduces a function
from module1 import printinfo as p1
from module2 import printinfo as p2
#  You can add... By renaming the name . Function name is used to introduce 
p1()
p2()
 Copy code 

It is worth noting that , If not used here as If renaming , Because there are two printinfo It will lead to mistakes , So you need to rename it

__name__ == '__main__' Usage of

__name__ yes Python An implicit variable in represents the name of the module , If you print directly __name__, Then there is __main__.

Sample code module.py

def printinfo():
    print(" This is the content of the function ")

print(__name__)
print(" This is outside the module function ")
 Copy code 

Output results

# __main__
#  This is outside the module function 
 Copy code 

If you will module.py Introduced as a module Then the printed result is the name of the module ( No path 、 Extension )

Sample code

import module
 Copy code 

Output results

module
 This is outside the module function 
 Copy code 

At this time, the output result is different , Simply speaking : stay module.py Own eyes name Namely main, However, in the eyes of other documents name Namely module.

hold module.py modified

def printinfo():
    print(" This is the content of the function ")

printinfo()
if __name__=="__main__":
    print(__name__)
    print(" This is outside the module function ")
 Copy code 

Output results

 This is the content of the function 
__main__
 This is outside the module function 
 Copy code 

When other files are imported

import module
 Copy code 

Output results

 This is the content of the function 
 Copy code 

Because other files will not be executed in the module when they are imported if The code when the condition holds Because the name of the module is module instead of __main__

__name__ == '__main__' It is very useful in practical scenarios , Generally, the module must be tested in the process of writing , You can't print out the test results when importing , If you delete , When you want to improve the module, you have to write it again , This is the time __name__ == '__main__' That's where it comes in

Scope of variable

Please look at the following code :

def test():
    b = " This is the variable of the function "

    def test_nested():
        c = " This is a nested function variable "
        print(a)
        print(b)
        print(c)
    test_nested()


if __name__ == "__main__":
    a = " This is the global scope "
    test()
 Copy code 

According to this code , To understand the scope of variables

At this point in the function test_nested In vivo call a,b,c None of the three functions will report any errors ,

If you call... Outside the function b The variable will report

print(b)
NameError: name 'b' is not defined
 Copy code 

Variable b Undefined error , because b It's a local variable , It's part of the local scope , It is not accessible outside the function

If in test Function body calls c Will report

print(c)
NameError: name 'c' is not defined
 Copy code 

Variable c Undefined error , because c Is in test_nested Function body , about test Function belongs to local scope , But for test intra-function test_nested In terms of functions , Variable b Belongs to nested scope , stay test_nested We can access it in the function .

If you pass global to b Promoted to a global variable , Call... Outside the function b The variable will print normally

nonlocal Keywords can only act on local variables , And always find the variables in the upper local scope closest to the current

def outer():
    aa = 111

    def inner():
        nonlocal aa
        aa = 222
        print(aa)
    inner()
    print(aa)


outer()
 Copy code 

If you don't have this nonlocal Keyword is the function body inner Print 222, The body of the function outer Print 111, After addition, two... Will be printed directly 222

Python When looking for a variable, it will follow “ Local scope ”-->“ Nested scope ”-->“ Global scope ”-->“ Built-in scope ” Search in order , So-called “ Built-in scope ” Namely Python Built in identifiers , Used before inputprintint Etc. are built-in scopes .

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301043554256.html

Random recommended