本文重点:解决了类里面定义的装饰器,在同一个类里面使用的问题,并实现了装饰器的类属性参数传递

目录:

一、基本装饰器

二、在类里定义装饰器,装饰本类内函数

三、类装饰器

正文:

一、基本装饰器

装饰不带参数的函数def clothes(func):

def wear():

print('Buy clothes!{}'.format(func.__name__))

return func()

return wear

@clothes

def body():

print('The body feels could!')

#备注:@是语法糖

# 不用语法糖的情况下,使用下面语句也能实现装饰作用:把body再加工,再传给body

# body = clothes(body)

装饰带一个参数的函数def clothes(func):

def wear(anything): # 实际是定义一个anything参数,对应body函数参数

print('Buy clothes!{}'.format(func.__name__))

return func(anything) # 执行func函数,并传入调用传入的anything参数

# wear = func(anything) # 在这一步,实际上可以看出来,为啥wear必须带参数,因为它就是func(anything)

return wear

# 所以clothes的结果是

# clothes = wear = func(anything)

# 不用语法糖的情况下就是

# body = clothes(body)('hands')

# 进一步证明:print(body.__name__) 显示的是wear函数

@clothes

def body(part):

print('The body feels could!{}'.format(part))

body('hands')

装饰带不定长参数的函数

通常装饰器不只装饰一个函数,每个函数参数的个数也不相同

这个时候使用不定长参数*args,**kwargsdef clothes(func):

def wear(*args, **kwargs):

print('Buy clothes!{}'.format(func.__name__))

return func(*args, **kwargs)

return wear

@clothes

def body(part):

print('The body feels could!{}'.format(part))

@clothes

def head(head_wear, num=2):

print('The head need buy {} {}!'.format(num, head_wear))

body('hands')

head('headdress')

装饰器带参数# 把装饰器再包装,实现了seasons传递装饰器参数。

def seasons(season_type):

def clothes(func):

def wear(*args, **kwargs):

if season_type == 1:

s = 'spring'

elif season_type == 2:

s = 'summer'

elif season_type == 3:

s = 'autumn'

elif season_type == 4:

s = 'winter'

else:

print('The args is error!')

return func(*args, **kwargs)

print('The season is {}!{}'.format(s, func.__name__))

return func(*args, **kwargs)

return wear

return clothes

@seasons(2)

def children():

print('i am children')

children()

二、在类里定义装饰器,装饰本类内函数:

类装饰器,装饰函数和类函数调用不同的类函数

把装饰器写在类里

在类里面定义个函数,用来装饰其它函数,严格意义上说不属于类装饰器。class Buy(object):

def __init__(self, func):

self.func = func

# 在类里定义一个函数

def clothes(func): # 这里不能用self,因为接收的是body函数

# 其它都和普通的函数装饰器相同

def ware(*args, **kwargs):

print('This is a decrator!')

return func(*args, **kwargs)

return ware

@Buy.clothes

def body(hh):

print('The body feels could!{}'.format(hh))

body('hh')

装饰器装饰同一个类里的函数

背景:想要通过装饰器修改类里的self属性值。class Buy(object):

def __init__(self):

self.reset = True # 定义一个类属性,稍后在装饰器里更改

self.func = True

# 在类里定义一个装饰器

def clothes(func): # func接收body

def ware(self, *args, **kwargs): # self,接收body里的self,也就是类实例

print('This is a decrator!')

if self.reset == True: # 判断类属性

print('Reset is Ture, change Func..')

self.func = False # 修改类属性

else:

print('reset is False.')

return func(self, *args, **kwargs)

return ware

@clothes

def body(self):

print('The body feels could!')

b = Buy() # 实例化类

b.body() # 运行body

print(b.func) # 查看更改后的self.func值,是False,说明修改完成

三、类装饰器

定义一个类装饰器,装饰函数,默认调用__call__方法#

class Decrator(object):

def __init__(self, func): # 传送的是test方法

self.func = func

def __call__(self, *args, **kwargs): # 接受任意参数

print('函数调用CALL')

return self.func(*args, **kwargs) # 适应test的任意参数

@Decrator # 如果带参数,init中的func是此参数。

def test(hh):

print('this is the test of the function !',hh)

test('hh')

定义一个类装饰器,装饰类中的函数,默认调用__get__方法

实际上把类方法变成属性了,还记得类属性装饰器吧,@property

下面自已做一个propertyclass Decrator(object):

def __init__(self, func):

self.func = func

def __get__(self, instance, owner):

'''

instance:代表实例,sum中的self

owner:代表类本身,Test类

'''

print('调用的是get函数')

return self.func(instance) # instance就是Test类的self

class Test(object):

def __init__(self):

self.result = 0

@Decrator

def sum(self):

print('There is the Func in the Class !')

t = Test()

print(t.sum) # 众所周知,属性是不加括号的,sum真的变成了属性

做一个求和属性sum,统计所有输入的数字的和class Decrator(object):

def __init__(self, func):

self.func = func

def __get__(self, instance, owner):

print('调用的是get函数')

return self.func(instance)

class Test(object):

def __init__(self, *args, **kwargs):

self.value_list = []

if args:

for i in args:

if str(i).isdigit():

self.value_list.append(i)

if kwargs:

for v in kwargs.values():

if str(v).isdigit():

self.value_list.append(v)

@Decrator

def sum(self):

result = 0

print(self.value_list)

for i in self.value_list:

result += i

return result

t = Test(1,2,3,4,5,6,7,8,i=9,ss=10,strings = 'lll')

print(t.sum)

python装饰器传递参数_Python装饰器高级版—Python类内定义装饰器并传递self参数...相关推荐

  1. Python装饰器高级版—Python类内定义装饰器并传递self参数

    本文重点:解决了类里面定义的装饰器,在同一个类里面使用的问题,并实现了装饰器的类属性参数传递 目录: 一.基本装饰器 二.在类里定义装饰器,装饰本类内函数 三.类装饰器 正文: 一.基本装饰器 装饰不 ...

  2. python 类装饰器和函数装饰器区别_python进阶之装饰器之4在类中定义装饰器,将装饰器定义为类,两者的区别与联系...

    # 把装饰器定义为类 # 定义中需要实现__call__(),__get__() 方法 import types from functools import wraps class Profiled: ...

  3. python如何调整图片大小_Python基础进阶 - 如何使用Python调整图像大小

    Python已成为编程语言的首选.不仅适用于一般的面向对象的编程,还适用于各种科学,数学,统计等应用. 由于强大的开发人员社区已经使用Python开发了用于各种目的的库和API,因此所有这些都是可能的 ...

  4. java类中定义索引器,C#面向对象基础——字段、属性和索引器

    关于面向对象编程,在很多语言里面都出现过,最常用的如java和c++, C#语言关于面向对象编程的规范,我觉得介于上面两者之间,我的理解是它比较偏向c++,或许是因为跟它的析构函数有关系,像java有 ...

  5. python高阶函数教学_Python 简明教程 --- 16,Python 高阶函数

    对于那些快速算法,我们总是可以拿一些速度差不多但是更容易理解的算法来替代它们. -- Douglas Jones 目录 高阶函数一般以函数为参数. 本节我们介绍Python 中三个方便的高阶函数,分别 ...

  6. python中迭代器有哪些_Python迭代器:什么是Python中的迭代器以及如何使用它?

    Python编程语言已经扩展了创新的每一个方面,包括机器学习.数据科学.人工智能等,这些概念是Python作为编程语言取得成功的基石.在本文中,我们将通过以下概念来理解Pytho Python编程语言 ...

  7. python编写字符串查找函数_Python 简明教程 --- 8,Python 字符串函数

    好代码本身就是最好的文档.当你需要添加一个注释时,你应该考虑如何修改代码才能不需要注释. -- Steve McConnell 目录 字符串有很多操作函数,所以,这里我们专门用一节来介绍这些函数. 建 ...

  8. python编写一个弹球游戏_Python实战案例:用Python写一个弹球游戏,就是这么强

    我们前面讲了几篇关于类的知识点,为了让大家更好的掌握类的概念,并灵活的运用这些知识,我写了一个有趣又好玩的弹球的游戏,一来可以把类的知识融会一下,二来加深对Python的兴趣.你会发现哎呀Python ...

  9. python海龟作图好看图案_python海龟绘图,其实python也很强大,这些技能你知道吗?...

    Turtle库 简介 什么是Turtle 首先,turtle库是一个点线面的简单图像库,能够完成一些比较简单的几何图像可视化.它就像一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始 ...

最新文章

  1. 正则表达式最常用的符号匹配
  2. C#之windows桌面软件第十三课:C#中常用的类有哪些?构造函数怎么用?
  3. java实现愤怒的小鸟游戏
  4. “不翻身,就要翻船”!帆软独家:制造业数字化转型解决方案
  5. git学习之简介(一)
  6. matlab的梯形公式推导公式,复化梯形公式,辛普森公式的matlab程序
  7. pyspark 空值填充
  8. 弘辽科技:拼多多店铺星级多久更新一次?如何提升?
  9. 3d打印英语文献_万华推出可3D打印PP粉末材料
  10. 平面与空间射影几何小结——空间射影几何
  11. hget hmget redis api使用
  12. 一文讲解AGV机器人的12种导航导引方式,收藏备用
  13. 苹果创始人沃兹尼亚克:喜欢小米 乔布斯没那么神!
  14. MySQL数据库——语句
  15. NaN表示什么?typeof NaN结果是什么?
  16. 构建供销一体化电商交易体系,数商云S2B2B系统实现锂电池企业全面转型升级
  17. mysql 计算农历_MySQL 获取农历年函数
  18. 【NVM】NVM 常用笔记
  19. 第五十讲:神州路由器IPv6隧道的配置
  20. 将标签进行One-hot编码

热门文章

  1. checksec未完待续~
  2. c语言指针官方解释_C语言中的指针解释了–它们并不像您想象的那么难
  3. React Router教程–如何使用代码示例渲染,重定向,切换,链接等
  4. docker下使用mongodb
  5. 【linux命令】Centos下如何匹配内容在哪个文件中
  6. SpringBoot中 pagehelper插件使用
  7. Java-时间复杂度和空间复杂度
  8. 垃圾回收(三)-gc模块
  9. 漫步微积分一 —— 引言
  10. Java Spring连接Tibco Queue 总结