Full-stack python development, Day6, and python development day6
Introduction to functions of python
Now I have a question: Can variables in the function be directly referenced outside the function?
Def func1 (): m = 1 print (m) # This row reports an error
Execution error:
NameError: name 'M' is not defined
Why is the above error reported? Now let's analyze how python works internally:
First, let's recall how functions are implemented when Python code is run. After the Python interpreter is executed, it opens up a space in the memory. Whenever a variable is encountered, the relationship between the variable name and value is recorded. However, when a function is defined, the interpreter only symbolically reads the function name as memory, indicating that the function already exists, the interpreter does not care about the internal variables and logic of the function.
When the function is called, the Python interpreter will open up another memory to store the content in the function. At this time, it will focus on the variables in the function, the variables in the function are stored in the newly opened memory. The variables in the function can only be used inside the function. As the function is executed, all the content in the memory will be cleared.
We created a namespace named ------- for the space that stores the relationship between names and values.
At the beginning of the code execution, the space created to store the "relationship between variable names and values" is calledGlobal namespace;
The temporary space opened during function execution is calledLocal namespace.
Ii. namespace and scope
Zen of python
import this
Execution output:
The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one-- and preferably only one --obvious way to do it.Although that way may not be obvious at first unless you're Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it's a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea -- let's do more of those!
View Code
As mentioned in the Zen of python, namespace is a wonderful concept. Let's make full use of it!
There are three types of namespaces:
Global namespace
Local namespace
Built-in namespace
* Built-in namespaceThe python interpreter provides the following names: input, print, str, list, And tuple... they are all familiar to us.
The loading and value order between the three namespaces:
Loading Sequence: Built-in namespace (loading before running the program)-> global namespace (running: loading from top to bottom)-> local namespace (running: loading only when called)
Value Order:
In a local call: local namespace> global namespace> built-in namespace
In global call: global namespace-> built-in namespace
To sum up, when looking for variables, we can look for them from a small scope, one layer to a large scope.
Scope
Scope is the scope of action, which can be divided into global scope and local scope according to the effective scope.
GLOBAL SCOPE: IncludeBuilt-in namespace and global namespace, Can be referenced and globally valid at any location of the entire file
Local Scope: Local namespace, which can only take effect within a local range
Globals and locals Methods
Call globals and locals globally
Locally call locals and globals
Global keyword, nonlocal keyword.
Global:
1. Declare a global variable.
2. global (limited to strings and numbers) is used to modify global variables in a local scope ).
Example of global keywords:
def func(): global a a = 3func()print(a)count = 1def search(): global count count = 2search()print(count)
Execution output:
3
2
Ps: You can directly reference a variable data type (list, dict, set) without using global.
Examples of applications with variable data types:
li = [1,2,3]dic = {'a':'b'}def change(): li.append('a') dic['q'] = 'g' print(dic) print(li)change()print(li)print(dic)
Execution output:
{'A': 'B', 'q': 'G '}
[1, 2, 3, 'a']
[1, 2, 3, 'a']
{'A': 'B', 'q': 'G '}
Nonlocal:
1. Global variables cannot be modified.
2. In the local scope, the variables in the parent scope (or the outer scope is not the global scope) are referenced and modified, and the referenced layer is, all the variables at that layer and below are changed.
Example of the nonlocal Keyword:
def add_b(): b = 42 def do_global(): b = 10 print(b) def dd_nonlocal(): nonlocal b b = b + 20 print(b) dd_nonlocal() print(b) do_global() print(b)add_b()
Execution output:
10
30
30
42
3. Function nesting and scope chain
Nested function call
def max2(x,y): m = x if x>y else y return mdef max4(a,b,c,d): res1 = max2(a,b) res2 = max2(res1,c) res3 = max2(res2,d) return res3res = max4(23,-7,31,11)print(res)
Nested Function Definition
def f1(): print("in f1") def f2(): print("in f2") f2()f1()###########def f1(): def f2(): def f3(): print("in f3") print("in f2") f3() print("in f1") f2()f1()
Execution output:
In f1
In f2
In f1
In f2
In f3
Function scope chain: A small scope can use a large range of variables, but vice versa. It is unidirectional.
Example of a scope chain application
def f1(): a = 1 def f2(): def f3(): print(a) f3() f2()f1()################def f1(): a = 1 def f2(): a = 2 f2() print('a in f1 : ',a)f1()
Execution output:
1
A in f1: 1
Iv. essence of function names
The function name is essentially the memory address of the function.
1. can be referenced
def func(): print('in func')f = funcprint(f)
Execution output:
<Function func at 0x00000281719B7F28>
2. elements that can be used as container types
Def f1 (): print ('f1 ') def f2 (): print ('F2') def f3 (): print ('f3') l = [f1, f2, f3] d = {'f1 ': f1, 'F2': f2, 'f3': f3} # Call l [0] () d ['F2'] ()
Execution output:
F1
F2
3. It can be used as a function parameter and return value.
def f1(): print('f1')def func1(argv): argv() return argvf = func1(f1)f()
Execution output:
F1
F1
Concepts of first-class objects
The first-class object refers
1. can be created at runtime
2. It can be used as a function parameter or return value.
3. objects that can be stored in variables.
* Do not understand? Remember one sentence and use it as a common variable.
5. Closure
Def func (): name = 'White Venus 'def inner (): print (name)
Closure functions:
Internal functions include references to variables with external scopes rather than full-play scopes. These internal functions are called closure functions.
# An internal function is called an internal function.
With the scope, we cannot get the internal variables and functions of the function. What if we just want to do it? Back!
We all know that the variable in the function can be directly returned if we want to use it outside the function. What if we want to call the function inside the function outside the function?
Is it okay to directly return the name of this function?
This is the most common usage of closure functions.
def func(): name = 'eva' def inner(): print(name) return innerf = func()f()
Execution output: eva
Method _ closure _ for judging closure Functions __
# The output _ closure _ has a cell element: the closure function def func (): name = 'eva 'def inner (): print (name) print (inner. _ closure _) return innerf = func () f () # output _ closure _ is None: not the closure function name = 'egon' def func2 (): def inner (): print (name) print (inner. _ closure _) return innerf2 = func2 () f2 ()
Execution output:
(<Cell at 0x000002BDF5900B58: str object at 0x000002BDF5A85B20> ,)
Eva
None
Egon
Nested Closure
def wrapper(): money = 1000 def func(): name = 'eva' def inner(): print(name,money) return inner return funcf = wrapper()i = f()i()
Execution output:
Eva 1, 1000
Use closure functions to obtain network applications
from urllib.request import urlopendef index(): url = "http://www.py3study.com" def get(): return urlopen(url).read() return getxiaohua = index()content = xiaohua()print(content)
Execute and output a bunch of html code