装饰器
Posted jt925
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。
闭包:
如:
def func1():
a = 10
def func2():
print(a)
return func2
f = func1() # 此时得到func2,func1应该释放对应的内存
f() # 此时相当于运行 func2(),但由于func1已经执行完毕,按理说变量a应该不存在了,此时执行func2
因该报错才是,但事实是f()调用正常,这个现象叫做闭包。
总结:一个函数包含子函数,并且子函数调用了父函数下的变量,父函数的返回值为子函数的函数名,满足这种条件的函数叫做闭包
装饰器:
软件开发中的一个原则“开放-封闭”原则,简单来说,它规定已经实现的功能代码不允许被修改,但可以被扩展,即:
- 封闭:已实现的功能代码块不应该被修改
- 开放:对现有功能的扩展开放
函数未带参数:
user_status = False
def login(func):
def inner():
_username = "jiangsq" # 假装这是DB里存的用户信息
_password = "js123" # 假装这是DB里存的用户信息
global user_status
if user_status == False:
username = input("user:")
password = input("pasword:")
if username == _username and password == _password:
print("welcome login......")
user_status = True
else:
print("weong username or password!")
if user_status:
return func()
return inner
def home():
print(‘首页‘)
def america():
print(‘欧美专区‘)
@login
def japan():
print(‘日韩专区‘)
函数带参数:
user_status = False
def login(func):
def inner(arg):
_username = "jiangsq" # 假装这是DB里存的用户信息
_password = "js123" # 假装这是DB里存的用户信息
global user_status
if user_status == False:
username = input("user:")
password = input("pasword:")
if username == _username and password == _password:
print("welcome login......")
user_status = True
else:
print("weong username or password!")
if user_status:
return func(arg)
return inner
def home():
print(‘首页‘)
def america():
print(‘欧美专区‘)
@login
def japan(arg):
print(‘日韩专区‘)
print(arg)
japan(‘哈哈哈‘)
带参函数第二版:
user_status = False
def login(func):
def inner(*args,**kwargs):
_username = "jiangsq" # 假装这是DB里存的用户信息
_password = "js123" # 假装这是DB里存的用户信息
global user_status
if user_status == False:
username = input("user:")
password = input("pasword:")
if username == _username and password == _password:
print("welcome login......")
user_status = True
else:
print("weong username or password!")
if user_status:
return func(*args,**kwargs)
return inner
def home():
print(‘首页‘)
@login
def america():
print(‘欧美专区‘)
@login
def japan(arg):
print(‘日韩专区‘)
print(arg)
japan(‘哈哈哈‘)
america()
带参装饰器:
user_status = False
def login(auth_type):
def outer(func):
def inner(*args,**kwargs):
_username = "jiangsq" # 假装这是DB里存的用户信息
_password = "js123" # 假装这是DB里存的用户信息
global user_status
if user_status == False:
username = input("user:")
password = input("pasword:")
if username == _username and password == _password:
print("welcome login......")
user_status = True
else:
print("weong username or password!")
if user_status:
return func(*args,**kwargs)
return inner
return outer
def home():
print(‘首页‘)
@login(‘aaa‘) # 过程 login(‘eeee‘) =》 outer(japan) =》 inner()
def america():
print(‘欧美专区‘)
@login(‘eeee‘) # 过程 login(‘eeee‘) =》 outer(japan) =》 inner(arg)
def japan(arg):
print(‘日韩专区‘)
print(arg)
# japan(‘哈哈哈‘)
america()
# xx = login(‘qq‘) # outer
# japan = xx(japan)
# japan(‘哈哈哈‘)
装饰类的装饰器:
一、
# 描述符判断被描述的对象输入的类型是不是想要的类型
class miaoshufu:
def __init__(self, key, expected_type):
self.key = key
self.type = expected_type
def __set__(self, instance, value):
if type(value) is self.type:
instance.__dict__[self.key] = value
else:
print("%s传入的类型错误,应该是%s" %(value, self.type))
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __delete__(self, instance):
instance.__dict__.pop(self.key)
# 装饰器
def Typed(**kwargs):
def zhuang(obj):
for key,val in kwargs.items():
setattr(obj, key, miaoshufu(key,val))
# key = miaoshufu(str(key), val)
return obj
return zhuang
@Typed(name = str,age = int) # 不然要写很多,这样减少了重复代码
class People:
# name = miaoshufu(‘name‘, str)
# age = miaoshufu(‘age‘, int)
def __init__(self, name, age, salary, height):
self.name = name
self.age = age
self.salary = salary
self.height = height
p = People("wad", "awa", 10000, 173)
二、
def godme(fun):
def __godme(cls, *args, **kwargs):
print(‘before‘)
fun(cls, *args, **kwargs)
print(‘after‘)
return __godme
@godme
class Person:
def __new__(cls, *args, **kwargs):
print(‘__new__‘)
Person(Person)
以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章