1. How to use a function
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
2. Default parameter trap
2.1 For variable data types, immutable data types are not affected
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]
3. Namespace and scope
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
4. Closure The 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()
5. Parameters of the function
5.1 Definition stage
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.
5.2 Calling Phase
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
6. Decorator: Application of closure function
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
6.1 The implementation of decorators must follow two major principles
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
6.2 Decorator syntactic sugar
After being decorated Write the name of @decorator
on a separate line directly above the objectpython解释器一旦运行到@装饰器的名字,就会调用装饰器,然后将被装饰函数的内存地址当作参数传给装饰器,最后将装饰器调用的结果赋值给原函数名 foo=auth(foo) 此时的foo是闭包函数wrapper
6.3无参装饰器
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()
6.4有参装饰器
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')
7.题目
#题目一: 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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.