面向对象进阶之类装饰器及描述符

news/2024/4/26 23:40:46/文章来源:https://blog.csdn.net/hj1993/article/details/129151831

2. 类的装饰器

Python 中一切皆对象,装饰器同样适用于类:

无参数装饰器

def foo(obj):print('foo 正在运行~')return obj@foo   # Bar=foo(Bar)
class Bar:pass
print(Bar())
foo 正在运行~
<__main__.Bar object at 0x0000000004ED1B70>

有参数装饰器

利用装饰器给类添加类属性:

def deco(**kwargs):   # kwargs:{'name':'tom', 'age':1}def wrapper(obj):  # Dog、Catfor key, val in kwargs.items():setattr(obj, key, val)  # 设置类属性return objreturn wrapper@deco(name='tom', age=1)        # @wrapper ===> Dog=wrapper(Dog)
class Dog:pass
print(Dog.__dict__)         # 查看属性字典
print(Dog.name, Dog.age)@deco(name='john')
class Cat:pass
print(Cat.__dict__)
print(Cat.name)
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None, 'name': 'tom', 'age': 1}
tom 1
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Cat' objects>, '__weakref__': <attribute '__weakref__' of 'Cat' objects>, '__doc__': None, 'name': 'john'}
john

@deco(name='tom', age=1) 首先执行 deco(name='tom', age=1),返回 wrapper。再接着执行 @wrapper,相当于 Dog = wrapper(Dog)。最后利用 setattr(obj, key, value) 为类添加属性。

描述符+装饰器实现类型检查

class Descriptor:def __init__(self, key, expected_type):self.key = key     # 'name'self.expected_type = expected_type   # strdef __get__(self, instance, owner):    # self:Descriptor对象, instance:People对象,owner:Peoplereturn instance.__dict__[self,key]def __set__(self, instance, value):if isinstance(value, self.expected_type):instance.__dict__[self.key] = valueelse:raise TypeError('你传入的%s不是%s' % (self.key, self.expected_type))def deco(**kwargs):    # kwargs:{'name': 'str', 'age': 'int'}def wrapper(obj):   # obj:Peoplefor key, val in kwargs.items():setattr(obj, key, Descriptor(key, val))  # key:name、age   val:str、int return objreturn wrapper@deco(name=str, age=int)           # @wrapper ==> People = wrapper(People)
class People:
#     name = Descriptor('name', str)def __init__(self, name, age, color):self.name = nameself.age = ageself.color = color
p1 = People('rose', 18, 'white')
print(p1.__dict__)p2 = People('rose', '18', 'white')
{'__module__': '__main__', '__init__': <function People.__init__ at 0x00000000051971E0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'name': <__main__.Descriptor object at 0x00000000051BFDD8>, 'age': <__main__.Descriptor object at 0x00000000051D1518>}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-010cd074c06d> in <module>()30 print(People.__dict__)31 
---> 32 p2 = People('rose', '18', 'white')<ipython-input-18-010cd074c06d> in __init__(self, name, age, color)25     def __init__(self, name, age, color):26         self.name = name
---> 27         self.age = age28         self.color = color29 p1 = People('rose', 18, 'white')<ipython-input-18-010cd074c06d> in __set__(self, instance, value)11             instance.__dict__[self.key] = value12         else:
---> 13             raise TypeError('你传入的%s不是%s' % (self.key, self.expected_type))14 15 def deco(**kwargs):    # kwargs:{'name': 'str', 'age': 'int'}TypeError: 你传入的age不是<class 'int'>

在利用 setattr() 设置属性的时候,对 value 进行类型检查。

3. 自定制 property

静态属性 property 可以让类或类对象,在调用类函数属性时,类似于调用类数据属性一样。下面我们利用描述符原理来模拟 property。

把类设置为装饰器,装饰另一个类的函数属性:

class Foo:def __init__(self, func):self.func = funcclass Bar:@Foo      # test = Foo(test)def test(self):pass
b1 = Bar()
print(b1.test)
<__main__.Foo object at 0x00000000051DFEB8>

调用 b1.test 返回的是 Foo 的实例对象。

利用描述符模拟 property

class Descriptor:        # 1"""描述符"""def __init__(self, func):     # 4    # func: areaself.func = func  # 5def __get__(self, instance, owner):   # 13"""调用 Room.areaself: Descriptor 对象instance: Room 对象(即 r1或Room中的 self)owner: Room 本身"""res = self.func(instance)  #14 # 实现调用 Room.area,area需要一个位置参数 self,即 r1return res      # 17class Room:     # 2def __init__(self, name, width, height):   # 7self.name = name        # 8self.width = width     # 9self.height = height   # 10# area = Descriptor(area),Descriptor 对象赋值给 area,实际是给 Room 增加描述符# 设置 Room 的属性字典@Descriptor     # 3  def area(self):         # 15"""计算面积"""return self.width * self.height   # 16r1 = Room('卧室', 3, 4)    # 6
print(Room.__dict__)   # 11
print(r1.area)      # 12    调用 Descriptor.__get__()
{'__module__': '__main__', '__init__': <function Room.__init__ at 0x0000000005206598>, 'area': <__main__.Descriptor object at 0x000000000520C6A0>, 'test': <property object at 0x00000000051FFDB8>, '__dict__': <attribute '__dict__' of 'Room' objects>, '__weakref__': <attribute '__weakref__' of 'Room' objects>, '__doc__': None}
12

首先执行 @Descriptor,相当于 area = Descriptor(area),类似于给类 Room 设置 area属性。area 属性又被 Descriptor 代理(描述)。

所有当执行 r1.area 的时候,触发调用 Descriptor.__get__() 方法,然后执行 area() 函数,并返回结果。

到目前为止,模拟 property 已经完成了百分之八十。唯一不足的是:property 除了可以使用实例对象调用外,还可以使用类调用。只不过返回的是 property 这个对象:

class Room:...@propertydef test(self):return 1
print(Room.test)
<property object at 0x000000000520FAE8>

那么我们也用类调用看看:

print(Room.area)
AttributeError: 'NoneType' object has no attribute 'width'

发现类没有 width 这个属性,这是因为我们在使用 __get__() 方法时,其中 instance 参数接收的是类对象,而不是类本身。当使用类去调用时,instance = None

因此在使用模拟类调用时,需要判断是否 instance 为 None:

def __get__(self, instance, owner):if instance == None:return self...
print(Room.area)
<__main__.Descriptor object at 0x0000000005212128>
​````
发现返回的是 Descriptor 的对象,与 property 的返回结果一样。到此为止,我们使用描述符成功地模拟 property 实现的功能。**实现延迟计算功能**要想实现延迟计算功能,只需每计算一次便缓存一次到实例属性字典中即可:
​```python
def __get__(self, instance, owner):if instance == None:return selfres = self.func(instance)  setattr(instance, self.func.__name__, res)return res...
print(r1.area)  # 首先在自己的属性字典中找,自己属性字典中有 area 属性。因为已经缓存好上一次的结果,所有不需要每次都去计算

总结

  • 描述符可以实现大部分 Python 类特性中的底层魔法,包括 @property、@staticmethod、@classmethod,甚至是 __slots__属性。
  • 描述符是很多高级库和框架的重要工具之一,通常是使用到装饰器或元类的大小框架中的一个组件。

4. 描述符自定制

4.1 描述符自定制类方法

类方法 @classmethod 可以实现类调用函数属性。我们也可以描述符模拟出类方法实现的功能:

class ClassMethod:def __init__(self, func):self.func = funcdef __get__(self, instance, owner):def deco(*args, **kwargs):return self.func(owner, *args, **kwargs)return decoclass Dog:name = 'tom'@ClassMethod  # eat = ClassMethod(eat) 相当于为 Dog 类设置 eat 类属性,只不过它被 Classmethod 代理def eat(cls, age):print('那只叫%s的狗,今年%s岁,它正在吃东西' % (cls.name, age))print(Dog.__dict__)
Dog.eat(2)     # Dog.eat:调用类属性,触发 __get__,返回 deco。再调用 deco(2)
{'__module__': '__main__', 'name': 'tom', 'eat': <__main__.ClassMethod object at 0x00000000052D1278>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
那只叫tom的狗,今年2岁,它正在吃东西

类 ClassMethod 被定义为一个描述符,@ClassMethod 相当于 eat = ClassMethod(eat)。因此也相当于 Dog 类设置了类属性 eat,只不过它被 ClassMethod 代理。

运行 Dog.eat(2),其中 Dog.eat 相当于调用 Dog 的类属性 eat,触发 __get__() 方法,返回 deco 。最后调用 deco(2)

4.2 描述符自定制静态方法

静态方法的作用是可以在类中定义一个函数,该函数的参数与类以及类对象无关。下面我们用描述符来模拟实现静态方法:

class StaticMethod:def __init__(self, func):self.func = funcdef __get__(self, instance, owner):def deco(*args, **kwargs):return self.func(*args, **kwargs)return decoclass Dog:@StaticMethoddef eat(name, color):print('那只叫%s的狗,颜色是%s的' % (name, color))print(Dog.__dict__)
Dog.eat('tom', 'black')d1 = Dog()
d1.eat('lila', 'white')
print(d1.__dict__)
{'__module__': '__main__', 'eat': <__main__.StaticMethod object at 0x00000000052EF940>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
那只叫tom的狗,颜色是black的
那只叫lila的狗,颜色是white的
{}

类以及类对象属性字典中,皆没有 name 和 color 参数,利用描述符模拟静态方法成功。

5. property 用法

静态属性 property 本质是实现了 get、set、delete 三个方法。

class A:@propertydef test(self):print('get运行')@test.setterdef test(self, value):print('set运行')@test.deleterdef test(self):print('delete运行')a1 = A()
a1.test
a1.test = 'a'
del a1.test
get运行
set运行
delete运行

另一种表现形式:

class A:def get_test(self):print('get运行')def set_test(self, value):print('set运行')def delete_test(self):print('delete运行')test = property(get_test, set_test, delete_test)a1 = A()
a1.test
a1.test = 'a'
del a1.test
get运行
set运行
delete运行

应用

class Goods:def __init__(self):self.original_price = 100self.discount = 0.8@propertydef price(self):"""实际价格 = 原价 * 折扣"""new_price = self.original_price * self.discountreturn new_price@price.setterdef price(self, value):self.original_price = value@price.deleterdef price(self):del self.original_priceg1 = Goods()
print(g1.price)		# 获取商品价格
g1.price = 200		# 修改原价
print(g1.price)
del g1.price
80.0
160.0

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_72843.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构与算法(二)(Python版)

数据结构与算法&#xff08;一&#xff09;&#xff08;Python版&#xff09; 文章目录递归动规初识递归&#xff1a;数列求和递归三定律递归的应用&#xff1a;任意进制转换递归的应用&#xff1a;斐波那契数列递归调用的实现分治策略与递归优化问题和贪心策略找零兑换问题贪心…

系列四、多表查询

一、多表关系 项目开发中&#xff0c;在进行数据库表结构设计时&#xff0c;会根据业务需求及业务模块之间的关系&#xff0c;分析并设计表结 构&#xff0c;由于业务之间相互关联&#xff0c;所以各个表结构之间也存在着各种联系&#xff0c;基本上分为三种&#xff1a;一对多…

Sprng依赖注入(二):setter注入是如何工作的?

文章示例环境配置信息jdk版本:1.8开发工具&#xff1a;Intellij iDEA 2020.1springboot:2.3.9.RELEASE前言在Spring依赖注入&#xff08;一&#xff09;&#xff1a;字段注入的方式是如何工作的&#xff1f;中主要分享了Spring bean依赖注入方式中的字段注入方式及其工作过程&a…

基于Pytorch,从头开始实现Transformer(编码器部分)

Transformer理论部分参考知乎上的这篇文章 Transformer的Attention和Masked Attention部分参考知乎上的这篇文章 Transformer代码实现参考这篇文章&#xff0c;不过这篇文章多头注意力实现部分是错误的&#xff0c;需要注意。 完整代码放到github上了&#xff0c;链接 Trans…

联想小新 Air-14 2019IML电脑 Hackintosh 黑苹果efi引导文件

原文来源于黑果魏叔官网&#xff0c;转载需注明出处。硬件型号驱动情况主板Lenovo LNVNB161216处理器Intel Core i5-10210U / i7-10510U已驱动内存8GB DDR4 2666已驱动硬盘康佳KAK0500B128(128 GB/固志硬盘)已驱动显卡Intel UHD 620Nvidia GeForce MX250(屏蔽)无法驱动声卡Cone…

轮播图、阅读注册协议、网页时钟、随机点名、小米搜索框、轮播图点击切换——web APIs练习

目录 一、获取元素&#xff08;DOM&#xff09; 1. 随机轮播图案例 2. 阅读注册协议&#xff08;定时器间歇函数的应用&#xff09; 3. 轮播图定时器版 4. 网页时钟 二、事件基础&#xff08;DOM&#xff09; 1. 随机点名案例 2. 轮播图点击切换&#xff08;重点&#…

【计算机网络 -- 期末复习】

例题讲解 IP地址&#xff08;必考知识点&#xff09; 子网掩码 子网划分 第一栗&#xff1a; 子网划分题目的答案一般不唯一&#xff0c;我们主要采用下方的写法&#xff1a; 第二栗&#xff1a; 路由跳转 数据传输 CSMA/CD数据传输 2、比特率与波特率转换 四相位表示&am…

ElasticSearch 学习笔记总结(一)

文章目录一、 数据的 分类二、 ElasticSearch 介绍三、 ElasticSearch 搭建四、正排索引 和 倒排索引五、ES HTTP 索引 操作六、ES HTTP 文档 操作七、ES HTTP 查询数据1. 条件查询2. 分页查询3. 排序查询4. 多条件查询5. 全文检索 完全匹配 高亮显示6. 聚合查询八、 ES HTTP 映…

Scalable but Wasteful: Current State of Replication in the Cloud

文章目录ABSTRACT1 INTRODUCTION2 REPLICATION IN THE WILD3 CURRENT APPROACHES TO SCALING STATE MACHINE REPLICATION4 EFFICIENCY METRIC5 INEFFECTIVENESS OF CURRENT APPROACHES PER NEW METRIC6 CONCLUSION AND FUTURE DIRECTIONSABSTRACT 共识协议是部署在基于云的存储…

面试热点题:stl中vector与list的优缺点对比、以及list的迭代器与vector迭代器的区别

vector的优点 下标随机访问 vector的底层是一段连续的物理空间&#xff0c;所以支持随机访问尾插尾删效率高 跟数组类似&#xff0c;我们能够很轻易的找到最后一个元素&#xff0c;并完成各种操作cpu高速缓存命中率高 因为系统在底层拿空间的时候&#xff0c;是拿一段进cpu&am…

Linux:基于libevent读写管道代码,改进一下上一篇变成可以接收键盘输入

对上一篇进行改进&#xff0c;变成可以接收键盘输入&#xff0c;然后写入管道&#xff1a; 读端代码&#xff1a; #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <s…

乌卡时代的云成本管理:从0到1了解FinOps

在上一篇文章中&#xff0c;我们介绍了企业云业务的成本构成以及目前面临的成本困境&#xff0c;以及当前企业逐步转向 FinOps 的行业趋势&#xff0c;这篇文章我们将详细聊聊 FinOps&#xff0c;包括概念、重要性以及成熟度评价指标。 随着对云服务和供应商的使用越来越多&…

Sms多平台短信服务商系统~完成阿里云短信服务发送可自行配置

1.项目中引入Maven 阿里云地址 不同编程语言都有对应的SDK,你们下载自己需要的即可。 pom.xml中添加maven坐标 <!--阿里云短信服务--><dependency><groupId>com.aliyun</groupId><artifactId>alibabacloud-dysmsapi20170525</artifactId>…

【UE4 制作自己的载具】1-使用3dsmax制作载具

学习谌嘉诚课程所做笔记源视频链接&#xff1a;【虚幻4】UE4雪佛兰科迈罗汽车详细制作中文教程&#xff01;&#xff08;汽车骨骼绑定驾驶、动画蓝图&#xff09;汽车模型下载链接&#xff1a;https://pan.baidu.com/s/1ZH5gaAwckzRIZ0w6n0qvIA密码&#xff1a;19sj步骤&#x…

系列五、事务

一、事务简介 1.1、定义 事务是一组操作的集合&#xff0c;它是一个不可分割的工作单位&#xff0c;事务会把所有的操作作为一个整体一起向系 统提交或撤销操作请求&#xff0c;即这些操作要么同时成功&#xff0c;要么同时失败。 例如: 张三给李四转账1000块钱&#xff0c;张…

Codeforces Round #848 (Div. 2)(A~D)

A. Flip Flop Sum给出一个只有1和-1的数组&#xff0c;修改一对相邻的数&#xff0c;将它们变为对应的相反数&#xff0c;修改完后数组的和最大是多少。思路&#xff1a;最优的情况是修改一对-1&#xff0c;其次是一个1一个-1&#xff0c;否则修改两个1。AC Code&#xff1a;#i…

2023-02-22 学习记录--TS-邂逅TS(二)

TS-邂逅TS&#xff08;二&#xff09; 不积跬步&#xff0c;无以至千里&#xff1b;不积小流&#xff0c;无以成江海。&#x1f4aa;&#x1f3fb; 一、接口&#xff08;interface&#xff09; 在 ts 中&#xff0c;子类只能继承一个父类&#xff0c;不可多继承&#xff0c;但是…

学习国家颁布的三部信息安全领域法律,理解当前工作中的信息安全合规要求

目录三部信息安全领域的法律文件三部法律的角色定位与联系三部法律的适用范围三部法律的主要履职部门三部法律条文章节结构中的共性三部法律中的一些次重点章节网络安全法的重点章节数据安全法的重点章节个人信息保护法的重点章节关于工业和信息化部行政执法项目清单三部信息安…

ChatGPT这是要抢走我的饭碗?我10年硬件设计都有点慌了

前 言 呃……问个事儿&#xff0c;听说ChatGPT能写电路设计方案了&#xff0c;能取代初级工程师了&#xff1f;那我这工程师的岗位还保得住么&#xff1f;心慌的不行&#xff0c;于是赶紧打开ChatGPT问问它。 嘿&#xff0c;还整的挺客气&#xff0c;快来看看我的职业生涯是否…

非关系型数据库(mongodb)简单使用介绍

关系型数据库与非关系型数据库 关系型数据库有mysql、oracle、db2、sql server等&#xff1b; 关系型数据库特点&#xff1a;关系紧密&#xff0c;由表组成&#xff1b; 优点&#xff1a; 易于维护&#xff0c;都是使用表结构&#xff0c;格式一致&#xff1b; sql语法通用&a…