清明假期结束,开始更新
python 装饰器:
##装饰器 在不改变原有代码的前提下,为原函数扩展新功能
@符号 装饰器的标识符
1 自动的把下面修饰的原函数当作参数传递给装饰器
2 把返回的新函数去替换原函数
# 装饰器的原型
def func():
print("hello world")
def extend1(_func):
def newfunc():
print("hello")
_func()
print("world")
return newfunc
func = extend1(func)
func()
# @ 符号的使用
def extend(_func):
def newfunc():
print("hello")
_func()
print("world")
return newfunc
@extend
def func():
print("hello world")
func()
#3.装饰器的嵌套
def extend1(_func):
def newfunc():
print("world")
_func()
print("hello")
return newfunc
def extend2(_func):
def newfunc():
print("hello")
_func()
print("world")
return newfunc
@extend1
@extend2
def func():
print("hello world")
func()
#4 用装饰器扩展带有参数的原函数
def extend(_func):
def newfunc(who,where):
print("hello")
_func(who,where)
print("world")
return newfunc
@extend
def func(who,where):
print("{},{}".format(who,where))
#func()
#5.用装饰器扩展带参数和返回值的原函数
def extend(_func):
def newfunc(*args,**kwargs):
print("hello")
res = _func(*args,**kwargs)
print("world")
return res
return newfunc
@extend
def func(*args,**kwargs):
lst = []
dic = {"a":"A","b":"B"}
for k,v in kwargs.items():
if k in dic:
strvar = dic[k] + v
lst.append(strvar)
return lst
#6使用类装饰器
class extend():
def __call__(self,_func):
return self._extend(_func)
def _extend(self,func):
def newfunc():
print("hello")
func()
print("world")
return newfunc
#方式一
@extend._extend
def func():
print("hello world")
func()
#方式二
@extend()
def func():
print("hello world")
#7. 带有参数的函数装饰器
def outer(num):
def extend(_func):
def newfunc1(_func):
print("hello")
_func()
print("world")
def newfunc2(_func):
print("hello")
_func()
print("world")
if num == 1:
return newfunc1
elif num == 2:
return newfunc2
return extend
class MyClass():
@outer(1)
def func1(self):
print("func1")
@outer(2)
def func2(self):
print("func2")
#8.带有参数的类装饰器
'''
参数1 给修饰的类添加成员方法和属性
参数2 把类中的run方法变成属性
'''
class extend():
ad = "vip"
def money(self):
print("money")
def __init__(self,num):
self.num = num
def __call__(self,cls):
if self.num == 1:
return self.extend1(cls)
elif self.num == 2:
return self.extend2(cls)
def extend1(self,cls):
def newfunc():
cls.ad = extend.ad
cls.money = extend.money
return cls()
return newfunc
@extend(1)
class MyClass():
def run():
return "run"
obj = MyClass()
print(obj.ad)
#9.类中的方法
'''
1.普通无参方法
2.绑定方法 1.绑定到对象, 2 绑定到类
3.静态方法 无论对象还是类 都不会默认传递任何参数
'''
class Dog():
#普通无参
def run():
print("run")
#绑定到对象方法
def eat(self):
print("eat")
#绑定到类的方法
@classmethod
def drink(cls):
print("drink")
#静态方法
@staticmethod
def jump():
print("jump")