Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python's function

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use the function of Python". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the function of Python".

1. How to use functions

Define first and then call. The definition phase only detects syntax and does not execute code.

In the invocation phase, start executing the code

All functions have a return value

There are no parameters when defining and no parameters when calling

There must be parameters when defining and calling.

two。 Default parameter trap 2.1 for variable data types, immutable and unaffected def c (a = []): a.append (1) print (a) c () c () c ()

Results:

[1]

[1, 1]

[1, 1, 1]

Def c (a = []): a.append (1) print (a) c ([]) c ([]) c ([])

Results:

[1]

[1]

[1]

3. Namespaces and scope

A namespace is a place where a name is bound to a value memory address (memory space)

Whenever the value must be found through the name, access to the name must look up the namespace

Namespaces are divided into three categories

Built-in namespace: the name that comes with the python interpreter is stored

Life cycle: takes effect when the interpreter is started, and fails when the interpreter is closed

Global namespace: the file-level name is stored

Life cycle: takes effect when the interpreter interprets and executes the python file, and becomes invalid after the file has been executed

Local namespace: a name defined within a function

Life cycle: the local namespace of the function is only temporarily generated when the function is called, and the function is invalidated when the function is called

Loading sequence

Built-in-> global-> local

The order in which names are found

Find up based on the current location

Suppose you are currently standing locally. Search order: local-> global-> built-in.

Assume that you are currently standing globally. Search order: global-> built-in

The search order of the name is fixed in the function definition stage (that is, the search order of the name has been determined when the syntax is detected), regardless of the location of the function call.

That is to say, wherever a function is called, it must go back to the location where the function was defined to determine the lookup relationship of the name.

Scope: scope refers to the scope of action.

Global scope: contains names in built-in namespaces and global namespaces

Features: global effectiveness, global survival

Local scope: contains names in the local namespace

Features: local effective, temporary survival

Global: declare a name locally that comes from the global scope and can be used to modify global immutable types locally

Nonlocal: declares that a name comes from the scope of the current layer and can be used to modify the immutable type of the outer function locally.

4. Closure function

If 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 object to return the closure function to the global scope for use, thus breaking the hierarchical restrictions of the function.

The closure function provides a solution to pass the value for the function body.

Def func (): name='egon' def inner (): print (name) return innerinner = func () inner () 5. Parameter 5.1 definition phase of the function

Positional parameter

Parameters defined sequentially from left to right in the definition phase

Default parameter

It has been initialized and assigned in the definition phase

Keyword parameter

Free theme

Variable length parameter args

The location parameter of the overflow, packaged into tuples, accepted, and the variable name assigned to args

Named keyword parameter

Parameters placed between * and must be passed in the form of key=value

Variable length position parameter kwargs

The overflow keyword argument is packaged into a dictionary, accepted by * *, and assigned to the variable kwargs

Parameter and argument relationship: when a function is called, the value of the argument is bound to the variable name of the parameter. This binding takes effect temporarily and becomes invalid after the call ends.

5.2 call phase

Location argument

The invocation phase will correspond to the formal parameters one by one according to the values passed from left to right.

Keyword argument

In the calling phase, the parameter named according to the key=value form passes the value for the parameter.

For arguments with *, break them into positional arguments before passing values, and then assign values

For the * * in the argument, break it into keyword arguments before passing the value, and then assign the value

6. Decorator: application of closure function

A decorator is a tool used to add new functions to the decorated object.

* * Note: * * the decorator itself can be any callable object, and the object of the decorator can also be any callable object.

Why use decorators?

* * Open and closed principle: * * closed means closed to modification and open to expansion

6.1 the implementation of the decorator must follow two principles

1. Do not modify the source code of the decorated object`

two。 Do not modify the way the decorated object is called

The goal of the decorator is to add new functions to the decorated object while following the principles of 1 and 2.

6.2 decorator grammar sugar

Write the name of the @ decorator on a separate line directly above the decorated object

Once the python interpreter runs to the @ decorator name, it calls the decorator, then passes the memory address of the decorated function as a parameter to the decorator, and finally assigns the result of the decorator call to the original function name foo=auth (foo), where foo is the closure function wrapper.

6.3 No-parameter decorator import timedef 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@timmerdef foo (): time.sleep (3) print ('from foo') foo () 6.4.Parametric decorator 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 wrapperreturn auth3@auth (driver='file') def foo (name): print (name) foo ('egon') 7. Topic # topic 1: 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') # topic two import time Randomuser= {'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 wrapperdef 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 ['user'] = name user [' login_time'] = time.time () res=func (* args) * * kwargs) return res return wrapper@authdef index (): time.sleep (random.randrange (3)) print ('welcome to index') @ authdef home (name): time.sleep (random.randrange (3)) print (' welcome% s to home'% name) index () home ('egon') # topic 3: simple version import requestsimport oscache_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 'https://www.python.org')# print (res) # topic 4: extended version import requests,os,hashlibengine_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'))# topic five route _ dic= {} def make_route (name): def deco (func): route_ [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) # topic 6 import timeimport osdef 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 () Thank you for your reading The above is the content of "how to use the function of Python". After the study of this article, I believe you have a deeper understanding of how to use the function of Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report