• Python基础笔记(四)


    1. 返回函数与闭包

    如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)

    def getSum(*args):
        def add():
            result = 0
            for i in args:
                result = result + i
            return result
        return add
    
    myFun = getSum(1, 2, 3)
    
    print(myFun())
    # 6
    

    2. 装饰器(decorator)

    装饰器是对函数的一种包装,它使函数的功能得到扩展,但又不用修改函数内部的代码;一般用于增加函数执行前后的行为。
    下面的例子演示了在一个函数执行前打印当前时间,执行后打印执行完成的提示:

    import time
    
    def myDecorator(func):
        def myWrapper(*args, **kw):
            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
            f = func(*args, **kw)
            print(func.__name__, "function is called.")
            return f
        return myWrapper
    
    @myDecorator
    def hello():
        print("hello world")
    
    hello()
    # 2019-04-09 11:38:29
    # hello world
    # hello function is called.
    

    下面的例子演示了在一个函数返回字符串后,在该字符串前后加上HTML标签:

    def setTag(tag):
        def myDecorator(func):
            def myWrapper(*args, **kw):
                beginTag = "<" + tag + ">"
                endTag = "</" + tag + ">"
                return beginTag + func(*args, **kw) + endTag
            return myWrapper
        return myDecorator
    
    @setTag("div")
    def hello(name):
        return "hello, " + name
    
    print(hello("wayne"))
    # <div>hello, wayne</div>
    

    3. 偏函数(partial function)

    偏函数是通过将一个函数的部分参数预先绑定为特定值,从而得到一个新的具有较少可变参数的函数。
    下面的例子用偏函数实现了一个转换二进制的函数int2

    import functools
    
    int2 = functools.partial(int, base=2)
    
    print("%d %d" % (int("1010101"), int2("1010101")))
    # 1010101 85
    

    partial接收三个参数,形式为:partial(func, *args, **keywords),上面演示了只提供**keywords的情况,下面的例子演示了只提供*args的情况:

    import functools
    
    max2 = functools.partial(max, 10)
    
    print(max2(5, 6, 7))
    # 等效于max(10, 5, 6, 7)
    # 10
    

    4. 模块

    编写模块的一般格式如下:
    test1.py

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    'my test1 module'
    
    __author__ = "Wayne"
    
    import sys
    
    def init():
        print(sys.argv)
    
    if __name__ == '__main__':
        init()
    

    当通过命令行的方式运行该模块文件时,Python解释器把一个特殊变量__name__置为__main__。
    sys.argv返回的是一个list,执行python3 test1.py,那么sys.argv得到的list是['test1.py'];执行python3 test1.py A B,那么sys.argv得到的list是['test1.py', 'A', 'B']

  • 相关阅读:
    VS2005下安装boost
    NOIP2017宝藏 [搜索/状压dp]
    SCOI2008奖励关 [状压dp]
    莫队算法解析
    SCOI2005 互不侵犯 [状压dp]
    Codeforces ----- Kefa and Dishes [状压dp]
    TSP问题之状压dp法
    NOI2001炮兵阵地 [状压dp]
    状压dp入门
    「网络流24题」餐巾计划问题
  • 原文地址:https://www.cnblogs.com/CoderWayne/p/10873874.html
Copyright © 2020-2023  润新知