Define first and then call it. In the definition phase, only the syntax is detected and the code is not executed.
In the calling phase, start Execution code
Functions all have return values
There are no parameters when defining, and there are no parameters when calling
There are parameters when defining, and there must be parameters when calling
def c(a=[]): a.append(1) print(a) c() c() c()
Result:
[1]
[ 1, 1]
[1, 1, 1]
def c(a=[]): a.append(1) print(a) c([]) c([]) c([])
Result:
[1]
[1]
[1]
The namespace is the place (memory space) used to store the binding relationship between the name and the value memory address
Any search The value must be through the name. To access the name, you must look up the namespace
The namespace is divided into three categories
Built-in namespace: It is stored in the python interpreter. The name
life cycle: takes effect when the interpreter is started, and becomes invalid when the interpreter is closed
Global name space: stores file-level names
Life cycle: It takes effect when the interpreter interprets and executes the python file, and becomes invalid after the file is executed.
Local namespace: The name defined within the function
Life cycle: This is only temporarily generated when the function is called. The local namespace of the function, which will be invalid after the function is called.
Loading order
Built-in->Global->Local
The order of searching names
Search upward based on the current location
Assuming that you are currently standing in the local area, the search order is: local->global->built-in
Assuming that you are currently standing in the global world, the search order is: global -> The search order of the built-in
names has been fixed during the function definition stage (that is, the search order of the names has been determined when checking the syntax). It has nothing to do with the calling position of the function
That is to say, no matter where the function is called, you must go back to the location where the function was originally defined to determine the search relationship of the name
Scope: Scope refers to It is the scope of action
Global scope: Contains the names in the built-in name space and the global name space
Features: Globally valid, global survival
Local scope: Contains names in the local namespace
Features: Locally valid, temporary survival
global: Declaring a name locally comes from the global scope and can be used to modify the global locally. Immutable type
nonlocal: Declare a name from the scope of the outer layer of the current layer, which can be used to locally modify the immutable type of the outer function
is defined inside the function and contains a reference to the scope name of the external function. It is necessary to combine the concept of function objects to return the closure function to the global scope for use, thereby breaking the hierarchical restrictions of the function
The closure function provides a solution for passing values into the function body
def func(): name='egon' def inner(): print(name) return inner inner = func() inner()
Position shape Parameters
Formal parameters defined in sequence from left to right in the definition phase
Default formal parameters
has been defined in the definition phase Its initialization assignment
Keyword parameters
Free theme
Variable length formal parameters args
Overflowed positional parameters, Packed into a tuple, given to accept, and assigned to the variable name of args
Named keyword parameters
Parameters placed between * and must follow key=value Format value transfer
Variable length positional parameters kwargs
Overflow keyword arguments are packed into a dictionary, accepted by **, and assigned to the variable kwargs
Form Relationship between parameters and actual parameters: When calling a function, the value of the actual parameter will be bound to the variable name of the formal parameter. This binding relationship is temporarily effective and will become invalid after the call is completed.
Positional parameters
In the calling phase, the values passed in from left to right will correspond to the formal parameters one-to-one
Keyword actual parameters
In the calling phase, the values are passed to the formal parameters according to the key=value format.
If there is * in the actual parameter, then the value is passed. Before passing the value, first break it into positional actual parameters, and then assign the value
The ** in the actual parameter, before passing the value, break it into keyword actual parameters, and then assign the value
Decorator is a tool used to add new functions to the decorated object
**Note:**The decorator itself can be anything A callable object, the decorated object can also be any callable object
Why use decorators
**Open and closed principle:**Closed refers to being closed to modifications and closed to extensions Open
1. Do not modify the source code of the decorated object`
2. Do not modify the call of the decorated object Method
The goal of the decorator is to add new functions to the decorated object under the premise of following the principles 1 and 2
After being decorated Write the name of @decorator
on a separate line directly above the objectpython解释器一旦运行到@装饰器的名字,就会调用装饰器,然后将被装饰函数的内存地址当作参数传给装饰器,最后将装饰器调用的结果赋值给原函数名 foo=auth(foo) 此时的foo是闭包函数wrapper
import time def timmer(func): def wrapper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) stop_time=time.time() print('run time is %s' %(stop_time-start_time)) return res return wrapper @timmer def foo(): time.sleep(3) print('from foo') foo()
def auth(driver='file'): def auth3(func): def wrapper(*args,**kwargs): name=input("user: ") pwd=input("pwd: ") if driver == 'file': if name == 'egon' and pwd == '123': print('login successful') res=func(*args,**kwargs) return res elif driver == 'ldap': print('ldap') return wrapper return auth3 @auth(driver='file') def foo(name): print(name) foo('egon')
#题目一: db='db.txt' login_status={'user':None,'status':False} def auth(auth_type='file'): def auth3(func): def wrapper(*args,**kwargs): if login_status['user'] and login_status['status']: return func(*args,**kwargs) if auth_type == 'file': with open(db,encoding='utf-8') as f: dic=eval(f.read()) name=input('username: ').strip() password=input('password: ').strip() if name in dic and password == dic[name]: login_status['user']=name login_status['status']=True res=func(*args,**kwargs) return res else: print('username or password error') elif auth_type == 'sql': pass else: pass return wrapper return auth3 @auth() def index(): print('index') @auth(auth_type='file') def home(name): print('welcome %s to home' %name) # index() # home('egon') #题目二 import time,random user={'user':None,'login_time':None,'timeout':0.000003,} def timmer(func): def wrapper(*args,**kwargs): s1=time.time() res=func(*args,**kwargs) s2=time.time() print('%s' %(s2-s1)) return res return wrapper def auth(func): def wrapper(*args,**kwargs): if user['user']: timeout=time.time()-user['login_time'] if timeout < user['timeout']: return func(*args,**kwargs) name=input('name>>: ').strip() password=input('password>>: ').strip() if name == 'egon' and password == '123': user['user']=name user['login_time']=time.time() res=func(*args,**kwargs) return res return wrapper @auth def index(): time.sleep(random.randrange(3)) print('welcome to index') @auth def home(name): time.sleep(random.randrange(3)) print('welcome %s to home ' %name) index() home('egon') #题目三:简单版本 import requests import os cache_file='cache.txt' def make_cache(func): def wrapper(*args,**kwargs): if not os.path.exists(cache_file): with open(cache_file,'w'):pass if os.path.getsize(cache_file): with open(cache_file,'r',encoding='utf-8') as f: res=f.read() else: res=func(*args,**kwargs) with open(cache_file,'w',encoding='utf-8') as f: f.write(res) return res return wrapper @make_cache def get(url): return requests.get(url).text # res=get('https://www.python.org') # print(res) #题目四:扩展版本 import requests,os,hashlib engine_settings={ 'file':{'dirname':'./db'}, 'mysql':{ 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'123'}, 'redis':{ 'host':'127.0.0.1', 'port':6379, 'user':'root', 'password':'123'}, } def make_cache(engine='file'): if engine not in engine_settings: raise TypeError('egine not valid') def deco(func): def wrapper(url): if engine == 'file': m=hashlib.md5(url.encode('utf-8')) cache_filename=m.hexdigest() cache_filepath=r'%s/%s' %(engine_settings['file']['dirname'],cache_filename) if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath): return open(cache_filepath,encoding='utf-8').read() res=func(url) with open(cache_filepath,'w',encoding='utf-8') as f: f.write(res) return res elif engine == 'mysql': pass elif engine == 'redis': pass else: pass return wrapper return deco @make_cache(engine='file') def get(url): return requests.get(url).text # print(get('https://www.python.org')) print(get('https://www.baidu.com')) #题目五 route_dic={} def make_route(name): def deco(func): route_dic[name]=func return deco @make_route('select') def func1(): print('select') @make_route('insert') def func2(): print('insert') @make_route('update') def func3(): print('update') @make_route('delete') def func4(): print('delete') print(route_dic) #题目六 import time import os def logger(logfile): def deco(func): if not os.path.exists(logfile): with open(logfile,'w'):pass def wrapper(*args,**kwargs): res=func(*args,**kwargs) with open(logfile,'a',encoding='utf-8') as f: f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__)) return res return wrapper return deco @logger(logfile='aaaaaaaaaaaaaaaaaaaaa.log') def index(): print('index') index()
The above is the detailed content of How to use Python functions. For more information, please follow other related articles on the PHP Chinese website!