zoukankan      html  css  js  c++  java
  • python学习笔记(1)

    1.匿名函数

          常规函数写法:

    def func():
        return True

       但是对于map这类方法参数为一个方法的,就可以使用匿名函数,而不用重新定义一个

    func = lambda x: True
    print(func())    # True

    2.函数名字

        对于方法而言,有一个名为__name__的内置属性,这个属性返回的是该方法的名字

    def func():
        return True
    print(func.__name__)    # func

    3.装饰器

        类似js里面的切片式编程,作用是在已经定义好的方法之前执行某些操作

    def log(func):
        def wrapper(*args, **kw):
            print("this func is:", func.__name__)
            return func(*args, **kw)
        return wrapper
    
    @log
    def now():
        print("2018/11/12")
    
    now()    #  this func is:now    
        2018/11/12

     4.偏函数

        对于部分参数较多的方法而言,可能需要通过二次封装来减少一些参数

    def say(name, sentence):
        print(name, ":", sentence)
    
    say("lilei", "hello")    #  lilei : hello
    say("hanmeimei", "hello")    # hanmeimei : hello
    
    say2 = lamdba name, sentence = "hello": say(name, sentence)
    say2("lilei")    # lilei : hello
    say2("hanmeimei", "world")    # hanmeimei : world

        但是,在参数过多的时候,就很麻烦了,需要把参数都处理一遍,functools提供了偏函数的方法,可以直接指定某个参数的默认值

    import functools
    say3 = functools.partial(say, sentence = "hello")
    say3("lilei")    #  lilei : hello
    say3("lilei", sentence = "world")    # lilei : world
    say3("lilei", "world")    #  TypeError: say() got multiple values for argument 'sentence'

    所以在需要重新赋值的时候,需要指定参数名

  • 相关阅读:
    (转)正则表达式与Python(RE)模块
    (转)【面试】【MySQL常见问题总结】【03】
    (转)MySQL性能调优my.cnf详解
    (转)python logging模块
    (转)python collections模块详解
    mysql故障总结
    rocksdb 编译安装 日志
    c++11 gcc4.8.x安装
    Install ssdb-rocks on CentOS 6
    在Shell里面判断字符串是否为空
  • 原文地址:https://www.cnblogs.com/timmer/p/9946534.html
Copyright © 2011-2022 走看看