from datetime import date, datetime
import numbers class IntField:
#数据描述符,实现以下任意一个,都会变为属性描述符
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value): #判断类型
if not isinstance(value, numbers.Integral):
raise ValueError("int value need")
if value < 0:
raise ValueError("positive value need")
self.value = value
def __delete__(self, instance):
pass class NonDataIntField:
#非数据属性描述符
def __get__(self, instance, owner):
return self.value class User:
age = IntField()
# age = NonDataIntField() '''
如果user是某个类的实例,那么user.age(以及等价的getattr(user,’age’))
首先调用__getattribute__。如果类定义了__getattr__方法,
那么在__getattribute__抛出 AttributeError 的时候就会调用到__getattr__,
而对于描述符(__get__)的调用,则是发生在__getattribute__内部的。
user = User(), 那么user.age 顺序如下: (1)如果“age”是出现在User或其基类的__dict__中, 且age是data descriptor, 那么调用其__get__方法, 否则 (2)如果“age”出现在user的__dict__中, 那么直接返回 obj.__dict__[‘age’], 否则 (3)如果“age”出现在User或其基类的__dict__中 (3.1)如果age是non-data descriptor,那么调用其__get__方法, 否则 (3.2)返回 __dict__[‘age’] (4)如果User有__getattr__方法,调用__getattr__方法,否则 (5)抛出AttributeError ''' # class User:
#
# def __init__(self, name, email, birthday):
# self.name = name
# self.email = email
# self.birthday = birthday
# self._age = 0
#
# # def get_age(self):
# # return datetime.now().year - self.birthday.year
#
# @property
# def age(self):
# return datetime.now().year - self.birthday.year
#
# @age.setter
# def age(self, value):
# #检查是否是字符串类型
# self._age = value if __name__ == "__main__":
user = User()
user.__dict__["age"] = "abc"
print (user.__dict__)
print (user.age)
# print (getattr(user, 'age'))
# user = User("bobby", date(year=1987, month=1, day=1))
# user.age = 30
# print (user._age)
# print(user.age)

元类编程--__get__ __set__属性描述符的更多相关文章

  1. __get__ __set__ __delete__描述符

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

  2. Python进阶开发之元类编程

    系列文章 √第一章 元类编程,已完成 ; 本文目录 类是如何产生的如何使用type创建类理解什么是元类使用元类的意义元类实战:ORM . 类是如何产生的 类是如何产生?这个问题肯定很傻.实则不然,很多 ...

  3. 3.python元类编程

     1.1.propety动态属性 在面向对象编程中,我们一般把名词性的东西映射成属性,动词性的东西映射成方法.在python中他们对应的分别是属性self.xxx和类方法.但有时我们需要的属性需要根据 ...

  4. Python元类编程

    来源:http://python.jobbole.com/88582/ @property装饰器,是将类中的函数当做属性调用 Python类中定义的属性,如果属性名前面只有一个下划线,那么就是一种规范 ...

  5. PythonI/O进阶学习笔记_7.python动态属性,__new__和__init__和元类编程(上)

    content: 上: 1.property动态属性 2.__getattr__和__setattr__的区别和在属性查找中的作用 3.属性描述符 和属性查找过程 4.__new__和__init__ ...

  6. gj8 元类编程

    8.1 property动态属性 from datetime import date, datetime class User: def __init__(self, name, birthday): ...

  7. Python 属性描述符和属性的查找过程

    属性描述符可以用来控制给属性赋值的时候的一些行为 import numbers class IntField: def __get__(self, instance, owner): return s ...

  8. python之属性描述符与属性查找规则

    描述符 import numbers class IntgerField: def __get__(self, isinstance, owner): print('获取age') return se ...

  9. 流畅的python第二十章属性描述符学习记录

    描述符是对多个属性运用相同存取逻辑的一种方式.例如,Django ORM 和 SQL Alchemy等 ORM 中的字段类型是描述符,把数据库记录中字段里的数据与 Python 对象的属性对应起来.描 ...

随机推荐

  1. *438. Find All Anagrams in a String 找到字符串中所有字母异位词

    1. 原始题目 给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引. 字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 201 ...

  2. Fastjson 序列化与反序列化

    JSON这个类是fastjson API的入口,主要的功能都通过这个类提供. 序列化API // 将Java对象序列化为JSON字符串,支持各种各种Java基本类型和JavaBean public s ...

  3. Silence Removal and End Point Detection MATLAB Code

    转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/08/silence-removal-and-end-point-detection.html ...

  4. SQL语句 update 字段=字段+字符串 拼接

    update user_info set user_name = concat(user_name,'呵呵呵') where user_name = '哈哈哈';

  5. k8s版jenkins--master/slave模式实现CI/CD---带solo开源博客项目--带maven、djk、git工具

    k8s环境: 192.168.0.91 master 192.168.0.92 node 192.168.0.96 gitlab 192.168.0.98 harbor k8s集群安装请参照:http ...

  6. Golang中的Map(集合)

    Map 是一种无序的键值对的集合.Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值. Map 是一种集合,所以我们可以像迭代数组和切片那样迭代它.不过,Map 是无 ...

  7. Django:将后台返回的数据填充到select下拉框中

    select选择框如下: <select data-placeholder="选择项目..." class="form-control" name=&qu ...

  8. 【OpenGL开发】关于GLEW扩展库

    GLEW是一个跨平台的C++扩展库,基于OpenGL图形接口.使用OpenGL的朋友都知道,window目前只支持OpenGL1.1的涵数,但 OpenGL现在都发展到2.0以上了,要使用这些Open ...

  9. ffmpeg.编译(20191129)

    1.一步步实现windows版ijkplayer系列文章之一——Windows10平台编译ffmpeg 4.0.2,生成ffplay - HarlanC - 博客园.html(https://www. ...

  10. python实践项目一:Collatz函数

    要求1:编写一个名为 collatz()的函数,它有一个名为 number 的参数.如果参数是偶数,那么 collatz()就打印出 number // 2, 并返回该值.如果 number 是奇数, ...