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

      

  • 相关阅读:
    WinForm 资源文件的使用
    php 常量
    netbean使用技巧
    netbeans 7安装xdebug调试php程序
    eclipse 开发技巧
    asp.net 获取客户机IP地址
    NameValueCollection详解
    Paramics插件编程进程间通讯
    Paramics API编程配置
    windows查询端口占用
  • 原文地址:https://www.cnblogs.com/zzay/p/14343048.html
Copyright © 2011-2022 走看看