python描述符的应用
使用描述符为python实现类型检测
class Typed:
def __get__(self, instance, owner):
print(instance)
print(owner)
def __set__(self, instance, value):
pass
class Girl:
name = Typed()
def __init__(self, name, age):
self.name = name # 我希望传入的name是str
self.age = age # 我希望传入的age是int
g = Girl("satori", 18)
g.name
'''
<__main__.Girl object at 0x03D28430>
<class '__main__.Girl'>
'''
# 可以看到当我们获取被代理的值,会触发get方法,instance就是Girl的实例对象
# owner则是Girl这个类
class Typed:
def __get__(self, instance, owner):
pass
def __set__(self, instance, value):
print(instance)
print(value)
class Girl:
name = Typed()
def __init__(self, name, age):
self.name = name # 我希望传入的name是str
self.age = age # 我希望传入的age是int
g = Girl("satori", 18)
'''
<__main__.Girl object at 0x03D28430>
satori
'''
# 可以看到当我们给被代理的值赋值的时候,会触发set方法,instance就是Girl的实例对象
# value则是我们赋的值
class Typed:
def __init__(self, key):
self.key = key
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __set__(self, instance, value):
instance.__dict__[self.key] = value
def __delete__(self, instance):
instance.__dict__.pop(self.key)
class Girl:
name = Typed("name")
age = Typed("age")
def __init__(self, name, age):
self.name = name
self.age = age
g = Girl("satori", 18)
print(g.__dict__)
g.name = "mashiro"
print(g.__dict__)
del g.name
print(g.__dict__)
'''
{'name': 'satori', 'age': 18}
{'name': 'mashiro', 'age': 18}
{'age': 18}
'''
# 等于说 我饶了一圈,并没有直接将属性添加的字典里面,而是向上找了代理,让代理帮我把属性添加的字典里面去
那么,接下来就可以实现类型检测了
class Typed:
def __init__(self, key, except_type):
self.key = key
self.except_type = except_type
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __set__(self, instance, value):
if isinstance(value, self.except_type):
instance.__dict__[self.key] = value
else:
raise Exception(f"{self.key} must be type {self.except_type}")
def __delete__(self, instance):
instance.__dict__.pop(self.key)
class Girl:
name = Typed("name", str)
age = Typed("age", int)
def __init__(self, name, age):
self.name = name
self.age = age
g = Girl("satori", 18)
print(g.__dict__) # {'name': 'satori', 'age': 18}
try:
import traceback
g = Girl("satori", "18")
except Exception:
print(traceback.format_exc())
'''
Exception: age must be type <class 'int'>
'''
# 于是我们便手动实现了python的类型检测
类的装饰器
# 装饰器不仅可以给函数用,还可以给类用
def deco(obj):
print("======")
return obj
@deco
class Girl:
def __init__(self, name, age):
self.name = name
self.age = age
g = Girl("satori", 18)
print(g.__dict__)
'''
======
{'name': 'satori', 'age': 18}
'''
描述符实现property
class LazeProperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
# 如果是类调用,那么instance为空
if instance is None:
return self
res = self.func(instance)
setattr(instance, self.func.__name__, res) # 将值设进去,如果有从字典里面找,没有再计算
return res
class Girl:
def __init__(self, name, age):
self.name = name
self.age = age
@LazeProperty # info = LazeProperty(info)
def info(self):
return f"my name is {self.name},age is {self.age}"
g = Girl("satori", 18)
print(g.info) # my name is satori,age is 18
print(Girl.info) # <__main__.LazeProperty object at 0x04EF3910>
python描述符的应用的更多相关文章
- 杂项之python描述符协议
杂项之python描述符协议 本节内容 由来 描述符协议概念 类的静态方法及类方法实现原理 类作为装饰器使用 1. 由来 闲来无事去看了看django中的内置分页方法,发现里面用到了类作为装饰器来使用 ...
- python描述符(descriptor)、属性(property)、函数(类)装饰器(decorator )原理实例详解
1.前言 Python的描述符是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题 ...
- 【转载】Python 描述符简介
来源:Alex Starostin 链接:www.ibm.com/developerworks/cn/opensource/os-pythondescriptors/ 关于Python@修饰符的文章可 ...
- python描述符descriptor(一)
Python 描述符是一种创建托管属性的方法.每当一个属性被查询时,一个动作就会发生.这个动作默认是get,set或者delete.不过,有时候某个应用可能会有 更多的需求,需要你设计一些更复杂的动作 ...
- python描述符 descriptor
descriptor 在python中,如果一个新式类定义了__get__, __set__, __delete__方法中的一个或者多个,那么称之为descriptor.descriptor通常用来改 ...
- Python描述符的使用
Python描述符的使用 前言 作为一位python的使用者,你可能使用python有一段时间了,但是对于python中的描述符却未必使用过,接下来是对描述符使用的介绍 场景介绍 为了引入描述符的使用 ...
- Python描述符 (descriptor) 详解
1.什么是描述符? python描述符是一个“绑定行为”的对象属性,在描述符协议中,它可以通过方法重写属性的访问.这些方法有 __get__(), __set__(), 和__delete__().如 ...
- python描述符和属性查找
python描述符 定义 一般说来,描述符是一种访问对象属性时候的绑定行为,如果这个对象属性定义了__get__(),__set__(), and __delete__()一种或者几种,那么就称之为描 ...
- Iterator Protocol - Python 描述符协议
Iterator Protocol - Python 描述符协议 先看几个有关概念, iterator 迭代器, 一个实现了无参数的 __next__ 方法, 并返回 '序列'中下一个元素,在没有更多 ...
- Python描述符以及Property方法的实现原理
Python描述符以及Property方法的实现原理 描述符的定义: 描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实了__get__(),__set__(),__delete__()中 ...
随机推荐
- JS:关于JS字面量及其容易忽略的12个小问题
简要 问题1:不能使用typeof判断一个null对象的数据类型 问题2:用双等号判断两个一样的变量,可能返回false 问题3:对于非十进制,如果超出了数值范围,则会报错 问题4:JS浮点数并不精确 ...
- MyBatis---简单增删改查的带事物的例子
本例子包含了对数据库表简单的增删改查的操作,并且包含事物.该例子只适用于MySQL数据库.该例子需要手动创建数据库以及数据库表 例子中所需要的jar包,详查MyBatis---简介 一个entity类 ...
- 【转】Git命令解说
3.12. Git branch 3.12.1. 总述 当第一次执行git init时,系统就会创建一个名为“master”的分支. 而其它分支则通过手工创建. 下面列举一些常见的分支策略: ...
- X的N次方。N比较大。
final static long DIV = 1000000009; //分治法, 注意java类型为long, C++为__int64或 long long public static long ...
- VSX-2 搭建项目
由于是公司的项目,也不可能直接拿过来写博客,所以准备搭建一个自己的VSX项目. 项目需求这里就不写了,大体可参考曾经的一篇文章,这个VSX项目就是用来简化插件式开发. 本文开始正式记录做这个VSX项目 ...
- visio2013密钥
66DNF-28W69-W4PPV-W3VYT-TJDBQ http://www.xiazaizhijia.com/rjjc/133264.html
- java5初学
1.Eclipse快捷键 alt + / 代码提示,例如自动创建main方法ctrl + d 删除当前行ctrl + alt + up/down 复制当前行alt + up/down 交换行ctrl ...
- 【视觉SLAM14讲】ch3课后题答案
1.验证旋转矩阵是正交矩阵 感觉下面这篇博客写的不错 http://www.cnblogs.com/caster99/p/4703033.html 总结一下:旋转矩阵是一个完美的矩阵——正交矩阵.①行 ...
- go语言的学习网站
1)http://www.runoob.com/go/go-data-types.html 2)https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/ ...
- jQuery选择器之元素选择器
元素选择器:根据给定(html)标记名称选择所有的元素. 描述: $('element') 搜索指定元素标签名的所有节点,这是一个合集的操作.同样的也有原生方法getElementsByTagName ...