08.3 属性描述符__get__ __set__ __delete__

# -*- coding: utf-8 -*- # @Time : 2021/8/1 18:31 # @Author : zy7y # @Gitee : https://gitee.com/zy7y # @File : attr_desc.py # @Project : PythonBooks class IntField: """ 当实现了 以下 三个魔术方法中都任意一个 这个类 就可以说是属性描述符 """ def __get__(self, instance, owner): pass def __set__(self, instance, value): print(instance, value) if not isinstance(value, int): raise ValueError("IntField 必须传入 int 类型") def __delete__(self, instance): pass class NoData: """无数据描述符 实现 __get__魔法函数""" def __get__(self, instance, owner): print(owner) print(self.value) class User: age = IntField() # no = NoData() if __name__ == '__main__': user = User() # 执行赋值 操作时 会进入 IntField 中的 __set__ 魔法函数中 user.age = 123 print(user.__dict__) # 非 无数据描述符 不会进入到 user实例中
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章