Home > Backend Development > Python Tutorial > How to use Python functions

How to use Python functions

WBOY
Release: 2023-05-08 12:07:17
forward
1032 people have browsed it

    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()
    Copy after login

    Result:

    [1]
    [ 1, 1]
    [1, 1, 1]

    def c(a=[]):
        a.append(1)
        print(a)
    c([])
    c([])
    c([])
    Copy after login

    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()
    Copy after login

    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 object

    python解释器一旦运行到@装饰器的名字,就会调用装饰器,然后将被装饰函数的内存地址当作参数传给装饰器,最后将装饰器调用的结果赋值给原函数名 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()
    Copy after login

    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')
    Copy after login

    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[&#39;timeout&#39;]:
                    return func(*args,**kwargs)
            name=input(&#39;name>>: &#39;).strip()
            password=input(&#39;password>>: &#39;).strip()
            if name == &#39;egon&#39; and password == &#39;123&#39;:
                user[&#39;user&#39;]=name
                user[&#39;login_time&#39;]=time.time()
                res=func(*args,**kwargs)
                return res
        return wrapper
    
    @auth
    def index():
        time.sleep(random.randrange(3))
        print(&#39;welcome to index&#39;)
    
    @auth
    def home(name):
        time.sleep(random.randrange(3))
        print(&#39;welcome %s to home &#39; %name)
    
    index()
    home(&#39;egon&#39;)
    
    #题目三:简单版本
    import requests
    import os
    cache_file=&#39;cache.txt&#39;
    def make_cache(func):
        def wrapper(*args,**kwargs):
            if not os.path.exists(cache_file):
                with open(cache_file,&#39;w&#39;):pass
    
            if os.path.getsize(cache_file):
                with open(cache_file,&#39;r&#39;,encoding=&#39;utf-8&#39;) as f:
                    res=f.read()
            else:
                res=func(*args,**kwargs)
                with open(cache_file,&#39;w&#39;,encoding=&#39;utf-8&#39;) as f:
                    f.write(res)
            return res
        return wrapper
    
    @make_cache
    def get(url):
        return requests.get(url).text
    
    
    # res=get(&#39;https://www.python.org&#39;)
    
    # print(res)
    
    #题目四:扩展版本
    import requests,os,hashlib
    engine_settings={
        &#39;file&#39;:{&#39;dirname&#39;:&#39;./db&#39;},
        &#39;mysql&#39;:{
            &#39;host&#39;:&#39;127.0.0.1&#39;,
            &#39;port&#39;:3306,
            &#39;user&#39;:&#39;root&#39;,
            &#39;password&#39;:&#39;123&#39;},
        &#39;redis&#39;:{
            &#39;host&#39;:&#39;127.0.0.1&#39;,
            &#39;port&#39;:6379,
            &#39;user&#39;:&#39;root&#39;,
            &#39;password&#39;:&#39;123&#39;},
    }
    
    def make_cache(engine=&#39;file&#39;):
        if engine not in engine_settings:
            raise TypeError(&#39;egine not valid&#39;)
        def deco(func):
            def wrapper(url):
                if engine == &#39;file&#39;:
                    m=hashlib.md5(url.encode(&#39;utf-8&#39;))
                    cache_filename=m.hexdigest()
                    cache_filepath=r&#39;%s/%s&#39; %(engine_settings[&#39;file&#39;][&#39;dirname&#39;],cache_filename)
    
                    if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
                        return open(cache_filepath,encoding=&#39;utf-8&#39;).read()
    
                    res=func(url)
                    with open(cache_filepath,&#39;w&#39;,encoding=&#39;utf-8&#39;) as f:
                        f.write(res)
                    return res
                elif engine == &#39;mysql&#39;:
                    pass
                elif engine == &#39;redis&#39;:
                    pass
                else:
                    pass
    
            return wrapper
        return deco
    
    @make_cache(engine=&#39;file&#39;)
    def get(url):
        return requests.get(url).text
    
    # print(get(&#39;https://www.python.org&#39;))
    print(get(&#39;https://www.baidu.com&#39;))
    
    
    #题目五
    route_dic={}
    
    def make_route(name):
        def deco(func):
            route_dic[name]=func
        return deco
    @make_route(&#39;select&#39;)
    def func1():
        print(&#39;select&#39;)
    
    @make_route(&#39;insert&#39;)
    def func2():
        print(&#39;insert&#39;)
    
    @make_route(&#39;update&#39;)
    def func3():
        print(&#39;update&#39;)
    
    @make_route(&#39;delete&#39;)
    def func4():
        print(&#39;delete&#39;)
    
    print(route_dic)
    
    
    #题目六
    import time
    import os
    
    def logger(logfile):
        def deco(func):
            if not os.path.exists(logfile):
                with open(logfile,&#39;w&#39;):pass
    
            def wrapper(*args,**kwargs):
                res=func(*args,**kwargs)
                with open(logfile,&#39;a&#39;,encoding=&#39;utf-8&#39;) as f:
                    f.write(&#39;%s %s run\n&#39; %(time.strftime(&#39;%Y-%m-%d %X&#39;),func.__name__))
                return res
            return wrapper
        return deco
    
    @logger(logfile=&#39;aaaaaaaaaaaaaaaaaaaaa.log&#39;)
    def index():
        print(&#39;index&#39;)
    
    index()
    Copy after login

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template