How to use Python functions
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
