I. Namespaces and Scopes
Namespaces are mappings of names and objects, like dictionaries, where key is the variable name and value is the variable
1. Namespaces
Name= ' Egon ' #定义变量def func (): #定义函数 passclass Foo: #定义类 Pass
2. Classification of namespaces
(1) Built-in namespaces: As the Python interpreter starts, it includes exception types, built-in functions, and special methods, which can be called anywhere in the code
Print (sum) print (max) print (min) print (max ([builtinsfor])) Import i in Dir (builtins): #打印所有的内置函数 Print (i )
(2) Global namespace: The execution of a file produces a global namespace, meaning that the name of a file-level definition is placed in that space
X=1 #全局命名空间def func (): money=2000 #非全局 x=2 print (' func ') print (x) print (func) func ()
(3) Local namespace: A local namespace is generated when the function is called, and is only temporarily bound when the function is called, and the call ends the unbind
x=10000 #全局def func (): x=1 #局部 def f1 (): Pass
3. Scope
The visibility of namespaces is scope
- 1. Global scope: Built-in namespaces, global namespaces
- 2. Local scope: Local namespace
Name Lookup Order: Local Namespace---"Global namespace---" Built-in namespaces
View name in global scope: Gloabls ()
To view the name within a local scope: locals ()
Global scope Name: Globally valid, can be accessed anywhere, unless del is deleted, it will survive until file execution is complete
Local scope Name: Locally valid, can only be called at local scope, only valid at function call, end of call is invalidated
X=1000def func (y): x=2 print (Locals ()) print (Globals ()) Func (1)
Output:
{' Y ': 1, ' X ': 2} {' __loader__ ': <_frozen_importlib_external. Sourcefileloader object at 0x10c436c88>, ' __package__ ': None, ' __cached__ ': None, ' __file__ ': '/users/hexin/ pycharmprojects/py3/day4/2.py ', ' func ': <function func at 0x10c3c9f28>, ' __builtins__ ': <module ' builtins ' ( built-in), ' __spec__ ': None, ' __doc__ ': None, ' time ': <module ' time ' (built-in), ' __name__ ': ' __main__ ', ' x ': 1 000}
Four. Closure function
To put it simply, a closure is what you call a function A, and the function a returns a function B to you. The returned function, B, is called a closure.
The closure function must meet the following conditions:
1. Define the internal function;
2. Contains references to external scopes rather than global scopes;
Def f1 (): x = 1 def f2 (): print (x) return f2f=f1 () print (f) x=100f () print (x)
Output:
<function F1.<locals>.f2 at 0x107714400>1100
Application of closures
From urllib.request import urlopendef index (URL): def get (): return Urlopen (URL). Read () return getoldboy= Index (' http://crm.oldboyedu.com ') print (Oldboy (). Decode (' Utf-8 '))
Five. Decorative Device
1. Definition
Adorner: A tool that modifies others, modifies a function, and a tool refers to a function.
The adorner itself can be any callable object, the decorated object can also be any callable object
2. Why use adorners?
Open closure principle: Closed for modification, open for expansion
Adorners are designed to add new functionality to a decorated object without modifying its source code and calling mode.
3. The implementation of the adorner
The function of the adorner is to pass the decorated function as a parameter to the function corresponding to the adorner (the function with the same name), and return the wrapped decorated function "
Directly see, where a is a function corresponding to the adorner @a, B is the function of the adorner modifier, the role of the adorner @a is:
In short: @a is passing B to a () and returning the new B = A (b)
def a (name): #与装饰器对应的函数 return name () @a #装饰器 B = A (b) def b (): #被装饰函数 print (' hexin ')
Output
Hexin
The parsing process is like this:
1.python interpreter discovers @a, it calls its corresponding function (a function)
2.a function call to specify a parameter, passed in is the @a below the modified function, that is, B ()
3.a () function execution, call B (), B () print "Hexin"
Application of adorners
Import TimedefTimmer (func):defwrapper (): Start_time=time.time () func ()#index ()Stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnWrapper@timmer#Index=timmer (Index)defindex (): Time.sleep (1) Print('Welcome to Index') index () output: Welcome to Indexrun Time is1.005241870880127#--------------------------------------------------------------login_user={'User': None,'Status': False}defAuth (func):defWrapper (*args,**Kwargs):iflogin_user['User'] andlogin_user['Status']: Res=func (*args,**Kwargs)returnResElse: Name=input ('Please enter user name:') Password=input ('Please enter your password:') ifName = ='hexin' andPassword = ='123': login_user['User']='hexin'login_user['Status']=TruePrint('\033[45mlogin successful\033[0m') Res=func (*args,**Kwargs)returnResElse: Print('\033[45mlogin err\033[0m') returnWrapper@auth#Index=auth (Index)defindex ():Print('Welcome to Index page') @auth#Home=auth (Home)defHome (name):Print('%s Welcome to Home page'%name) index () Home ('hexin') Output: Please enter your user name: HEIXN Please enter your password:123Login Err Please enter your username: hexin Please enter your password:123Login Successfulhexin Welcome to Home Page
The basic frame of the adorner:
def timer (func): def wrapper (): func () return wrapper
With parameters
def timer (func): def wrapper (*args,**kwargs): func (*args,**kwargs) return wrapper
Python3 namespaces and scopes, closure functions, adorners