zoukankan      html  css  js  c++  java
  • 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实例中
    
    
    作者:zy7y
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    [状压DP][二分]JZOJ 3521 道路覆盖
    字符串操作
    练习: 判断一个数是否为小数
    Python 深浅拷贝
    编码
    python中的 == 和 is 的区别
    Python3 字典的增删改查
    Python3 列表的基本操作
    初识 Python
    方法的入门
  • 原文地址:https://www.cnblogs.com/zy7y/p/15087362.html
Copyright © 2011-2022 走看看