码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器

时间:2018-12-31 19:07:00      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:val   put   调用   inpu   WAD   else   value   运行   instance   

闭包:

如:

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)

装饰器

标签:val   put   调用   inpu   WAD   else   value   运行   instance   

原文地址:https://www.cnblogs.com/jt925/p/10202594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!