Python基础(第八章—函数下)

在这里插入图片描述
" 要是喜欢一个人、就要连同那个人的心脏一起喜欢 "


此篇文章装饰器借鉴于: Python 函数装饰器

1、高阶函数

1.1、高阶函数概念

高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足其一则为高阶函数

1.2、Python实例

  1. @1~3 全不是高阶函数
  2. @4 是高阶函数
@1 
# 列表作为参数传递、对此列表进行筛选操作从而来产生一个新的列表
def fun(list1):
    list2 = []
    for i in list1:
        if i % 2 == 0:
            list2.append(i)
    return list2
list1 = [1,2,3,4,5,6,7,8,9,10]
print(fun(list1))

输出:[2, 4, 6, 8, 10]

@2 
# 把判断条件作为一个新的函数嵌套在函数里面
def fun(list1):
      def fun1(i):
          if i % 2 == 0:
              return True
      list2 = []
      for i in list1:
          if fun1(i):
              list2.append(i)
      return list2
list1 = [1,2,3,4,5,6,7,8,9,10]
print(fun(list1))

输出:[2, 4, 6, 8, 10]

@3
# 把判断条件作为一个新的函数放在函数外面
def fun1(i):
    if i % 2 == 0:
        return True

def fun(list1):
      list2 = []
      for i in list1:
          if fun1(i):
              list2.append(i)
      return list2
list1 = [1,2,3,4,5,6,7,8,9,10]
print(fun(list1))

输出:[2, 4, 6, 8, 10]

@4
#  将函数作为参数传递
def fun1(i):
    if i % 2 == 0:
        return True


def fun(fun1,list1):
      list2 = []
      for i in list1:
          if fun1(i):
              list2.append(i)
      return list2
list1 = [1,2,3,4,5,6,7,8,9,10]
print(fun(fun1,list1))

输出:[2, 4, 6, 8, 10]

2、闭包

2.1、闭包概念

闭包:简单来说就是根据不同的配置信息得到不同的结果

专业解释:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。所以,有另一种说法认为闭包是由函数和与其相关的引用环境组合而成的实体

2.2、Python实例

  1. fun是一个函数、包括一个参数(a)、比较特殊的地方是这个函数里面又定义了一个新函数
  2. 新函数里面的一个变量正好是外部fun的参数(a)
  3. 也就是说、外部传递过来的参数(a)已经和sum_up函数绑定到一起了、形成了一个新函数
  4. 把(a)看做新函数的一个配置信息、配置信息不同、函数的功能就不一样了、也就是能得到定制之后的函数
  5. 再看看运行结果、我们发现、虽然p和q都是fun函数生成的、但是因为配置参数不同、后面再执行相同参数(100)的函数后得到了不同的结果、这就是闭包
def fun(a):
    def sum_up(b):
        return a + b
    return sum_up

p = fun(23)
q = fun(44)

print(p(100))
print(q(100))

输出:
	123
	144

3、匿名函数

3.1、lambda函数

lambda函数

  1. 专门来创建一些简单的函数
  2. 语法:lambda 参数:表达式
@1lambda创建简单的函数
fun1 = (lambda a,b:a+b)
print(fun1(10,20))

输出:30

@2 lambdafilter的结合
list1 = [1,2,3,4,5,6,7,8,9,10]
fun1 = (lambda i:i % 2 == 0)
print(list(filter(fun1,list1)))

输出:[2, 4, 6, 8, 10]

3.2、filter函数

filter函数

  1. 需要传递二个参数、按照自己的设定、过滤出想要的数据
  2. 传递一个参数(过滤设置)
  3. 传递一个需要过滤的序列(可迭代的)
list1 = [1,2,3,4,5,6,7,8,9,10]
def fun1(i):
    if i % 2 == 0:
        return True
a = filter(fun1,list1)
print(a)
print(list(a))
# 按照 fun1 函数里面的要求来对list1中的数据进行筛选
# 要用 lsit 方法将 filter 返回值转化为一个新的列表

输出:
	<filter object at 0x000001E70B86EA58>
	[2, 4, 6, 8, 10]	

*4、装饰器

4.1、装饰器概念

装饰器:装饰器(Decorators)是 Python 的一个重要部分、简单地说、他们是修改其他函数的功能的函数、有助于让我们的代码更简短、也更Pythonic(Python范儿)

4.2、一切皆对象

def hi(name="xiaohan"):
    return " hi " + name
 
print(hi())
# output: 'hi xiaohan'
 
# 我们甚至可以将一个函数赋值给一个变量,比如
greet = hi
# 我们这里没有在使用小括号,因为我们并不是在调用hi函数
# 而是在将它放在greet变量里头。我们尝试运行下这个
 
print(greet())
# output: 'hi xiaohan'
 
# 如果我们删掉旧的 hi 函数,看看会发生什么!
del hi
print(hi())
# output: NameError
 
print(greet())
# output: 'hi xiaohan'

4.3、在函数中定义函数

def hi(name="xiaohan"):
    print("now you are inside the hi() function")
 
    def greet():
        return "now you are in the greet() function"
 
    def welcome():
        return "now you are in the welcome() function"
 
    print(greet())
    print(welcome())
    print("now you are back in the hi() function")
 
hi()
# output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function
 
# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用
# 然后 greet() 和 welcome() 函数在 hi() 函数之外是不能访问的、比如:
 
greet()
# output: NameError: name 'greet' is not defined

4.4、从函数中返回函数

def hi(name="xiaohan"):
    def greet():
        return "now you are in the greet() function"
 
    def welcome():
        return "now you are in the welcome() function"
 
    if name == "xiaohan":
        return greet
    else:
        return welcome
 
a = hi()
print(a)
# output: <function greet at 0x7f2143c01500>
 
# 上面清晰地展示了 " a " 现在指向到 hi() 函数中的 greet() 函数
# 现在试试这个
 
print(a())
# 调用了 great 函数
# output: now you are in the greet() function

4.5、将函数作为参数传给另一个函数

def hi():
    return "hi xiaohan!"
 
def doSomethingBeforeHi(func):
    print("I am doing some boring work before executing hi()")
    print(func())
 
doSomethingBeforeHi(hi)
# output:I am doing some boring work before executing hi()
#        hi xiaohan!

4.6、创建一个装饰器

# 不使用 @
def a_new_decorator(a_func):
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
 
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")
 
a_function_requiring_decoration()
# output: "I am the function which needs some decoration to remove my foul smell"
 
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
# 现在函数 a_function_requiring_decoration 被函数 wrapTheFunction() 包装
 
a_function_requiring_decoration()
# output:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

# 使用 @
def a_new_decorator(a_func):
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
a_function_requiring_decoration()
# output: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()
 
# the @a_new_decorator 只是一种简短的说法:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

5、程序举例

5.1、Python time模块

借鉴于:Python时间模块之Time模块解析

  1. 使用该模块中的函数时,必须先引入该模块(import time)
  2. time.time():返回当前时间的时间戳
  3. time.localtime( [secs] ) 将一个时间戳转换为当前时区的struct_time、即时间数组格式的时间
# 模块 time.time()
import time
a = time.time()
print(a)
b = int(time.time())
print(b)

# output:1612504250.470374
#		  1612504250

# 模块 time.localtime( [secs] )
import time
a = time.localtime()
print(a)
# ouput:二种调用方法
print(a[0])
print(a.tm_year)

# output:time.struct_time(tm_year=2021, tm_mon=2, tm_mday=5, tm_hour=13, tm_min=52, tm_sec=58, tm_wday=4, tm_yday=36, tm_isdst=0)
#        2021
#        2021

5.2、实例

# 使用装饰器实现已存在的函数执行所花费的时间(time模块)
# 导入时间模块
import time

# 书写装饰器
# 被装饰的函数将被当做参数传入装饰器
def wrapper(func):
    # 内部函数
    def count_time(*args, **kwargs):
        start_time = time.time()
        # 获取代码开始运行的时间
        func(*args, **kwargs)
        # 调用需要计算运行时间的函数
        end_time = time.time()
        # 获取函数运行结束时的时间
        print("{}函数运行的时间为:{:.5f}秒".format(func.__name__, end_time - start_time))
    return count_time


# 测试
@wrapper
def test(n):
    time.sleep(n)
    print("运行结束了")


test(2)

# output:运行结束了
#         test函数运行的时间为:2.00063秒
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是我来晚了!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值