一、闭包:锁定数据,提高安全性,从函数外部调用函数内部定义的函数
"""闭包条件: >>> 作用:锁定数据,提高安全性
(1)函数中嵌套函数
(2)嵌套的函数引用了非全局变量a、b
(3)返回嵌套函数名
"""
def fun(a):
b = 100
def fun1():
print(a)
print(b)
return fun1
# 从函数外部调用函数内部定义的函数
res = fun(1999)
res()
# 把非全局变量a、b存储在私有属性closure中
print(res.__closure__)
二、装饰器:就是个闭包的应用。要使用装饰器,可以写个闭包函数。为原函数添加新的功能
(1)测试用例的前后置,准备数据和删除数据
(2)所有用例执行前的测试前置:登录
def login(fun1):
# 装饰了函数fun1,该函数条件满足if时执行被装饰的fun1()。
def fun():
user =input("输入账号:")
pw = input("输入密码:")
if user == "tfjiao" and pw == "123":
print("---开始执行登陆的代码---")
fun1()
return fun
@login
def index():
print("开始进入模块执行用例")
if __name__ == '__main__':
index()
# 输出
输入账号:tfjiao
输入密码:123
---开始执行登陆的代码---
开始进入模块执行用例
(3)python中类内置的三个装饰器:
# 类的装饰器
class Mytest():
# 类的私有属性,调用类时候自动调用它,进行初始化
def __init__(self, name):
self.name = name
# 类方法
@classmethod
def fun1(cls): # cls代表类本身
print("被@classmethod标记的fun1()是类方法,类方法可被调用Mytest.fun1(),也可Mytest().fun1()")
print(cls) # <class '__main__.Mytest'>
# 类的实例方法
def fun2(self):
print("类中没有被装饰的函数fun2()是类的实例方法,只能被实例调用")
print(self) # <__main__.Mytest object at 0x000002158F2FCE20>
# 类的静态方法,不常用,源码中经常可见
@staticmethod
def fun3():
print("被@staticmethod标记的fun3()是静态方法,不传self,可被类、类的实例调用")
# 只读属性 > 保证安全,防止别人篡改方法
@property
def fun4(self):
print("被@property标记的方法,该方法可像类的属性一样被调用,是只读属性")
return "tfjiao"
Mytest.fun1()
Mytest().fun2()
Mytest.fun3()
print(Mytest().fun4)
C:\Python39\python.exe C:/project/test_01.py
被@classmethod标记的fun1()是类方法,类方法可被调用Mytest.fun1(),也可Mytest().fun1()
<class '__main__.Mytest'>
类中没有被装饰的函数fun2()是类的实例方法,只能被实例调用
<__main__.Mytest object at 0x000002F35605EB50>
被@staticmethod标记的fun3()是静态方法,不传self,可被类、类的实例调用
被@property标记的方法,该方法可像类的属性一样被调用,是只读属性
tfjiao