zoukankan      html  css  js  c++  java
  • python

    装饰器+描述符

    实现给一个类添加属性且对添加的时,对属性进行类型审核:

    def zsq(**kwargs):
        def fun(obj):
            for i,j in kwargs.items():
                setattr(obj,i,mxf(i,j))
            return obj
        return fun
    
    class mxf():
        def __init__(self,na,ty):
            self.na = na
            self.ty = ty
        def __get__(self, instance, owner):
            return instance.ty
        def __set__(self, instance, value):
            if isinstance(value,self.ty):
                instance.__dict__[self.na] = value
            else:
                print("%s=%s 录入类型错误...."%(self.na,value))
    
    @zsq(name=str,old=int)
    class Student():
        def __init__(self,name,old):
            self.name = name
            self.old = old
    
    A1 = Student('anec',18)
    A2 = Student(4343,'123')
    print(A1.__dict__)
    print(A2.__dict__)
  • 相关阅读:
    2018.11.12
    2018.11.8
    2018.11.7
    2018.11.6
    2018.11.5
    学习python课程第七天
    作业四.
    学习python课程第六天
    作业3
    学习python课程第五天
  • 原文地址:https://www.cnblogs.com/Anec/p/9799702.html
Copyright © 2011-2022 走看看