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

AI Hentai Generator
Generate AI Hentai for free.

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 and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

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.
