• python类与对象-如何使用描述符对实例属性做类型检查


    如何使用描述符对实例属性做类型检查

    问题举例

    在某些项目中,我们实现一些类,并希望能像静态类型语言那样对它们的

    实例属性做类型检查:

      p = Persosn()

      p.name = 'tom' #必须是str

      p.age = 18       #必须是int

    要求:

    (1)可对实例属性指定类型

    (2)赋予不正确类型时抛出异常

    分析

    class A():
        pass
    
    a = A()
    #a.x = 'hello'
    #a.__dict__['x'] = 'hello'

    a.x = 'hello'等价于a.__dict__['x'] = 'hello', 需要类提供一个接口对属性所赋的值做类型检查,手动添加属性的值

    解决思路

    使用描述符来实现需要类型检查的属性:分别实现__get__, __set__, __delete__方法,在__set__中使用isinstance函数做类型检查

    代码

    class Attr:
        def __init__(self, key, type_):
            self.key = key
            self.type_ = type_
    
        def __set__(self, instance, value):
            print('in __set__')
            if not isinstance(value, self.type_):
                raise TypeError('must be %s' % self.type_)
            instance.__dict__[self.key] = value
    
        def __get__(self, instance, cls):
            print('in __get__', instance, cls)
            return instance.__dict__[self.key]
    
        def __delete__(self, instance):
            print('in __del__', instance)
            del instance.__dict__[self.key]
    
    class Person:
        name = Attr('name', str)
        age = Attr('age', int)
    
    p = Person()
    p.name = 'tom'
    #p.age = 20
    p.age = '20'

    参考资料:python3实用编程技巧进阶

  • 相关阅读:
    1mustache基本使用
    better-scroll
    PTA 题解:jmu-Java&Python-统计文字中的单词数量并按出现次数排序
    Java : Comparable 和 Comparator 接口
    java校验特殊符号
    vue项目左右布局的菜单效果,树形菜单
    响应式树形菜单导航,jq+ajax
    2020书单
    vite 为什么快
    vite 尝鲜
  • 原文地址:https://www.cnblogs.com/marton/p/10816512.html
Copyright © 2020-2023  润新知