python7:装饰器

1.调用外部程序

os.system-阻塞式调用

import os
#打开操作系统,可以输入命令
os.system("ipconfig")
retCode=os.system("mspaint")
print("retCode",retCode)
print("after")

画板打开并关闭后,才执行下一步打印操作
在这里插入图片描述

subprocess-python中的模块

subprocess.check_output:以字节形式返回,不能直接打印到控制台
subprocess.Popen:非阻塞式的,可以直接打印到控制台

import subprocess
#执行命令,将结果以字节形式返回,bytes
output_bytes=subprocess.check_output("ipconfig")
print(output_bytes.decode("gbk"))
print("=======after=========")#解码转为人能看懂的语言,mac写utf-8,windows写gbk

subprocess.Popen("ipconfig")
print("=========after================")

在这里插入图片描述

2.装饰器前戏

作用域

#解决Non-utf-8问题,在python代码最前面放这几行代码

Python file uses the following encoding: utf-8

(1)全局和局部-就近原则

先在自己这一层找
当局部变量和全局变量重名时:

  • 在局部作用域使用该变量,则使用局部变量
  • 在全局使用时,使用的是全局。
# This Python file uses the following encoding: utf-8
b = 99#全局变量
def foo():
    a=100#局部变量
    print(a)
    print(b)#局部作用域使用全局变量,可以
foo()

# print(a)#在全局使用局部变量,报错
print(b)# 全局作用域使用全局变量,可以

在这里插入图片描述

(2)嵌套作用域

# This Python file uses the following encoding: utf-8
b = 99#全局变量
def foo():
    a=100#局部变量
    print(a)
    print(b)#局部作用域使用全局变量,可以

    def bar():
        c=21#嵌套局部变量
        print("嵌套==",a,b,c)#嵌套作用域引用局部变量和全局变量
    bar()
  //  print(c)#局部引用内置嵌套局部变量,报错
foo()

# print(a)#在全局使用局部变量,报错
print(b)# 全局作用域使用全局变量,可以

在这里插入图片描述

(3)内置作用域、变量

系统内固定模块里预先定义好的变量:
name
os模块里的变量
在这里插入图片描述

高阶函数:函数是最高级的对象

(1)函数名可以被赋值给其他对象

def foo():
    print("我是一个函数对象")
a=foo#将函数对象赋给变量,a就具有了函数foo的特征
print(a)
b=foo()#调用函数,并将函数foo的返回值赋给变量b,b就等于foo的返回值
print(b)

在这里插入图片描述

(2)函数名当作参数传递

def foo1(func):
    func()
def bar():
    print("123")
foo1(bar)

在这里插入图片描述

(3)函数名可以作为返回值

#函数名可以作为返回值
def foo():
    def bar():
        print("过年啦")
    return bar
a=foo()
a()

在这里插入图片描述

闭包

在一个内部函数里边,对在外部作用域(但不是全局作用域)的变量进行引用,那么这个内部函数就被认为是闭包
在这里插入图片描述

#闭包
def outer():
    x=10
    def inner():
        print(x)
    return inner
a=outer()
a()

3.装饰器高阶

测试任务

装饰器概念

为已经存在的对象添加额外的功能
zhuang'shi
在这里插入图片描述

import time
#原本逻辑
def foo():
    print("执行了一些测试逻辑")
    time.sleep(1)
#新增计时逻辑
def show_time(func):
    def inner():
        begin_time=time.time()
        func()
        end_time=time.time()
        print("用例执行时间==",end_time-begin_time)
    return inner
foo=show_time(foo)
foo()

在这里插入图片描述
foo被装饰函数,show_time是装饰器(装饰函数),python提供了语法糖,在被装饰函数上@装饰器,这样就不用赋值了每次

import time
#新增计时逻辑
def show_time(func):
    def inner():
        begin_time=time.time()
        func()
        end_time=time.time()
        print("用例执行时间==",end_time-begin_time)
    return inner
#原本逻辑
@show_time
def foo():
    print("执行了一些测试逻辑")
    time.sleep(1)
# 省去了赋值的步骤,在外部看来相当于直接调用原函数
foo()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值