描述符应用

一、针对name属性的类型检查

class Type:
    def __init__(self,key):
        self.key = key

    def __get__(self, instance, owner):
        print("get方法")
        return instance.__dict__[self.key]

    def __set__(self, instance, value):
        print("set方法")
        if not isinstance(value,str):
            return "你传入的不是字符串"
        instance.__dict__[self.key] = value

    def __delete__(self, instance):
        print("正在执行delete")
        instance.__dict__.pop(self.key)

class People:
    name = Type('name')  #这样传入参数后,就可以让描述符去代理别的属性
    def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self.salary = salary
p1 = People('alex',13,13.3)
print(p1.name)
print(p1.__dict__)

  

但是上述代码只能针对字符串进行判断,所以需要改进

class Type:
    def __init__(self,key, exp_type):
        self.exp_type = exp_type
        self.key = key

    def __get__(self, instance, owner):
        print("get方法")
        return instance.__dict__[self.key]

    def __set__(self, instance, value):
        print("set方法")
        if not isinstance(value,self.exp_type):
            raise TypeError("你传入的类型不是",self.exp_type)   #高端玩法,主动引出错误
        instance.__dict__[self.key] = value

    def __delete__(self, instance):
        print("正在执行delete")
        instance.__dict__.pop(self.key)

class People:
    name = Type('name',str)  #这样传入参数后,就可以让描述符去代理别的属性
    age = Type('age',int)
    def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self.salary = salary
p1 = People('jinling',"18",13000)
print(p1.name)
print(p1.__dict__)

class Type:
    def __init__(self,key, exp_type):
        self.exp_type = exp_type
        self.key = key

    def __get__(self, instance, owner):
        print("get方法")
        return instance.__dict__[self.key]

    def __set__(self, instance, value):
        print("set方法")
        if not isinstance(value,self.exp_type):
            raise TypeError("你传入的类型不是",self.exp_type)
        instance.__dict__[self.key] = value

    def __delete__(self, instance):
        print("正在执行delete")
        instance.__dict__.pop(self.key)

class People:
    name = Type('name',str)  #这样传入参数后,就可以让描述符去代理别的属性
    age = Type('age',int)
    def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self.salary = salary
p1 = People('jinling',18,13000)
print(p1.name)
print(p1.__dict__)

  

  

posted @ 2019-10-11 17:53  绝世刘  阅读(137)  评论(0编辑  收藏  举报