zoukankan      html  css  js  c++  java
  • python3 使用数据描述器,验证字段类型

    class Typed:
    
        def __init__(self,type,name):
            self.type = type
            #name 存储变量
            self.name = name
    
        def __set__(self, instance, value):
            if not isinstance(value,self.type):
                raise ValueError(value)
            instance.__dict__[self.name] = value
    
    
        def __get__(self, instance, owner):
            value = instance.__dict__[self.name]
            return value
    
    #类中实现检查(inpsect)
    import inspect
    class TypeAssert:
    
        def __init__(self,cls):
            self.cls = cls
            params = inspect.signature(self.cls).parameters
            for name, param  in params.items():
                print(name, param.annotation)
                if param.annotation != param.empty:
                    setattr(self.cls,name,Typed(param.annotation,name)) #注入类属性
    
                    print(Typed.__dict__)
    
    
        def __call__(self, name,chinese,math):
            p = self.cls(name,chinese,math)
            return  p
    
    @TypeAssert
    class Student:
    
        def __init__(self, name:str,chinese:float, math:float):
            self.name = name
            self.chinese = chinese
            self.math = math
    
        def __repr__(self):
    
            return "student name:{} chinese:{} math:{}".format(self.name,self.chinese,self.math)
    
    
    c = Student('tom',66.3, 80.5)
    c2 = Student('jack',80.6, 99.5)
    
    print(c,c2)
    打印结果:student name:tom chinese:66.3 math:80.5 student name:jack chinese:80.6 math:99.5

      

  • 相关阅读:
    Java 线程之间的通讯,等待唤醒机制
    Java 死锁以及死锁的产生
    2018Java开发面经(持续更新)
    OpenFlow1.3协议wireshark抓包分析
    SDN核心技术剖析和实战指南---读书笔记
    Kafka常用命令
    安装kafka+zk-ui
    flink窗口
    flink架构原理
    安装Flink集群
  • 原文地址:https://www.cnblogs.com/zzay/p/14343048.html
Copyright © 2011-2022 走看看