http://www.cnblogs.com/linhaifeng/articles/6204014.html#_label12

描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),__set__(),__delete__()中的一个,这也被称为描述符协议
__get__():调用一个属性时,触发
__set__():为一个属性赋值时,触发
__delete__():采用del删除属性时,触发

定义一个描述符
class Foo: #在python3中Foo是新式类,它实现了三种方法,这个类就被称作一个描述符
def __get__(self, instance, owner):
pass
def __set__(self, instance, value):
pass
def __delete__(self, instance):
pass

描述符是干什么的:描述符的作用是用来代理另外一个类的属性的(必须把描述符定义成这个类的类属性,不能定义到构造函数中)

#描述符Str
class Str:
def __get__(self, instance, owner):
print('Str调用')
def __set__(self, instance, value):
print('Str设置...')
def __delete__(self, instance):
print('Str删除...') #描述符Int
class Int:
def __get__(self, instance, owner):
print('Int调用')
def __set__(self, instance, value):
print('Int设置...')
def __delete__(self, instance):
print('Int删除...') class People:
name=Str()
age=Int()
def __init__(self,name,age): #name被Str类代理,age被Int类代理,
self.name=name
self.age=age #何地?:定义成另外一个类的类属性 #何时?:且看下列演示 p1=People('alex',18)
'''
Str设置...
Int设置...
''' # #描述符Str的使用
p1.name # Str调用
p1.name='zhangsan' # Str设置...
del p1.name # Str删除...
#
# #描述符Int的使用
p1.age # Int调用
p1.age=18 # Int设置...
del p1.age # Int删除... # #我们来瞅瞅到底发生了什么
print(p1.__dict__) # {}
print(People.__dict__) # {'__weakref__': <attribute '__weakref__' of 'People' objects>,
# '__dict__': <attribute '__dict__' of 'People' objects>, '__doc__': None,
# '__init__': <function People.__init__ at 0x0000013E94AC5E18>, '__module__': '__main__',
# 'name': <__main__.Str object at 0x0000013E94AD81D0>, 'age': <__main__.Int object at 0x0000013E94AD8198>} # #补充
print(type(p1) == People) #type(obj)其实是查看obj是由哪个类实例化来的 True
print(type(p1).__dict__ == People.__dict__) # True
#描述符Str
class Str:
def __get__(self, instance, owner):
print('Str调用')
def __set__(self, instance, value):
print('Str设置...')
instance.__dict__['name'] = value
def __delete__(self, instance):
print('Str删除...') #描述符Int
class Int:
def __get__(self, instance, owner):
print('Int调用')
def __set__(self, instance, value):
print('Int设置...')
instance.__dict__['age'] = value
def __delete__(self, instance):
print('Int删除...') class People:
name=Str()
age=Int()
def __init__(self,name,age): #name被Str类代理,age被Int类代理,
self.name=name
self.age=age p1=People('alex',18)
print(p1.__dict__) # {'name': 'alex', 'age': 18}

描述符分两种
一 数据描述符:至少实现了__get__()和__set__()

 class Foo:
def __set__(self, instance, value):
print('set')
def __get__(self, instance, owner):
print('get')

非数据描述符:没有实现__set__()

class Foo:
def __get__(self, instance, owner):
print('get')

注意事项:

一 描述符本身应该定义成新式类,被代理的类也应该是新式类
二 必须把描述符定义成这个类的类属性,不能为定义到构造函数中
三 要严格遵循该优先级,优先级由高到底分别是
1.类属性
2.数据描述符
3.实例属性
4.非数据描述符
5.找不到的属性触发__getattr__()

#描述符Str
class Str:
def __init__(self,key):
self.key = key
def __get__(self, instance, owner):
print('Str调用')
return instance.__dict__[self.key]
def __set__(self, instance, value):
print('Str设置...')
if type(value) is not str:
raise TypeError("类型错误")
instance.__dict__[self.key] = value
def __delete__(self, instance):
print('Str删除...')
instance.__dict__.pop(self.key) #描述符Int
class Int:
def __init__(self,key):
self.key = key
def __get__(self, instance, owner):
print('Int调用')
return instance.__dict__[self.key]
def __set__(self, instance, value):
print('Int设置...')
if type(value) is not int:
raise TypeError("请输入int型")
instance.__dict__['age'] = value
def __delete__(self, instance):
print('Int删除...')
instance.__dict__.pop(self.key) class People:
name=Str("name")
age=Int("age")
def __init__(self,name,age): #name被Str类代理,age被Int类代理,
self.name=name
self.age=age p1=People("zhangsan",18)
print(p1.__dict__) # {'age': 18, 'name': 'zhangsan'}
print(p1.age)
del p1.age
print(p1.__dict__) # {'age': 18}

上面代码改进:

class Typed:
def __init__(self,key, expected_type):
self.key = key
self.expected_type = expected_type
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError("%s is not %s" %(value, self.expected_type))
instance.__dict__[self.key] = value
def __delete__(self, instance):
instance.__dict__.pop(self.key) class People:
name=Typed("name", str)
age=Typed("age", int)
def __init__(self,name,age): #name被Str类代理,age被Int类代理,
self.name=name
self.age=age #p1=People(99,18) # TypeError: 99 is not <class 'str'>
p1=People("zhangsan",'') # TypeError: 18 is not <class 'int'>

描述符__get__(),__set__(),__delete__()(三十七)的更多相关文章

  1. python基础----再看property、描述符(__get__,__set__,__delete__)

    一.再看property                                                                          一个静态属性property ...

  2. 描述符__get__,__set__,__delete__和析构方法__del__

    描述符__get__,__set__,__delete__ 1.描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),__set__(),__delete__()中的一 ...

  3. 描述符__get__,__set__,__delete__

    描述符__get__,__set__,__delete__ # 描述符:1用来代理另外一个类的属性 # __get__():调用一个属性时,触发 # __set__():为一个属性赋值时触发 # __ ...

  4. Python类总结-描述符__get__(),__set__(),__delete__()

    1 描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),set(),delete()中的一个,这也被称为描述符协议 get():调用一个属性时,触发 set():为一 ...

  5. python小知识-__call__和类装饰器的结合使用,数据描述符__get__\__set__\__delete__(描述符类是Python中一种用于储存类属性值的对象)

    class Decorator(): def __init__(self, f): print('run in init......') self.f = f def __call__(self, a ...

  6. Python描述符(__get__,__set__,__delete__)简介

    先说定义,这里直接翻译官方英文文档: 一般来说,描述符是具有“绑定行为”的对象属性,该对象的属性访问将会被描述符协议中的方法覆盖.这些方法是__get__(),__set__(),和__delete_ ...

  7. __get__ __set__ __delete__描述符

    描述符就是一个新式类,这个类至少要实现__get__ __set__ __delete__方法中的一种class Foo: def __get__(self, instance, owner): pr ...

  8. 描述符(__get__和__set__和__delete__)

    目录 一.描述符 二.描述符的作用 2.1 何时,何地,会触发这三个方法的执行 三.两种描述符 3.1 数据描述符 3.2 非数据描述符 四.描述符注意事项 五.使用描述符 5.1 牛刀小试 5.2 ...

  9. Python之路(第二十七篇) 面向对象进阶:内置方法、描述符

    一.__call__ 对象后面加括号,触发执行类下面的__call__方法. 创建对象时,对象 = 类名() :而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()( ...

随机推荐

  1. Webpack 2 视频教程

    这是我免费发布的高质量超清「Webpack 2 视频教程」. Webpack 作为目前前端开发必备的框架,Webpack 发布了 2.0 版本,此视频就是基于 2.0 的版本讲解的. 这个基本就是目前 ...

  2. 分布式监控系统Zabbix3.4-钉钉告警配置记录

    群机器人是钉钉群的高级扩展功能,群机器人可以将第三方服务的信息聚合到群聊中,实现自动化的信息同步.例如:通过聚合GitHub,GitLab等源码管理服务,实现源码更新同步:通过聚合Trello,JIR ...

  3. Week2 关于代码规范的一些认识

    代码规范 我觉得代码规范是有必要的,而对于以下的四个观点我要提出自己的反驳: 这些规范都是官僚制度下产生的浪费大家的编程时间.影响人们开发效率, 浪费时间的东西 首先应该明白,什么是“编码规范”?它不 ...

  4. Atcoder D - Knapsack 1 (背包)

    D - Knapsack 1 Time Limit: 2 sec / Memory Limit: 1024 MB Score : 100100 points Problem Statement The ...

  5. Java正则解析HTML一例

    import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { static String tes ...

  6. Linux环境(CentOS)安装维护过程中用到的常见命令

    1. yum 安装时需要选择仓库 一般的路径 /etc/repos.d/ 2. 查看安装了哪些软件的 yum list |grep docker installed 的就是已经安装的软件. 3. 卸载 ...

  7. js私有作用域(function(){})(); 模仿块级作用域

    摘自:http://outofmemory.cn/wr/?u=http%3A%2F%2Fwww.phpvar.com%2Farchives%2F3033.html js没有块级作用域,简单的例子: f ...

  8. Essential Phone PH1官方刷机方法

    Essential Phone官方有两种包 一种是ota包,即sideload线刷使用的包.但此刷机方法只能ota升级,不能降级. 另一种是Images包,即fastboot线刷使用的包.这种方法可以 ...

  9. 使用vscode 编写Markdown文件

    markdown简单语法参考下面简单事例: # 一级标题 1. 有序列表1 >1. 有序列表1 >>- *test1* >>- **test2** >>- * ...

  10. docker--命令详解

    查看版本: docker --version 查看docker信息: docker info 进入容器: docker exec -it bb /bin/bash #在容器中执行一个bash可以操作容 ...