2019年9月17日 描述符应用

1.描述符本事时新式类,被代理的类也应该是新式类

2.必须把描述符定义成类属性,不能定义到构造函数中

3.严格遵循优先级


class Typed:
    def __init__(self,k,t):#k 通过该方法将程序写活
        self.k=k
        self.t=t

    def __set__(self, instance, value):#从优先级考虑必须要有set方法,必须要定义成数据描述符,这样实例时候才能优先触发
        print('set方法',instance,value) #instance 就是实例本身p1,value就是赋给name的值。
        if not isinstance(value,self.t):
            print("%s没有传递%s格式"%(self.k,self.t))
            return
        instance.__dict__[self.k]=value #添加到实例到字典中

    def __get__(self, instance, owner):
        print('get方法',instance,owner)#owner 就是对应的类People
        return instance.__dict__[self.k] #取出实例中存储的值



class People:
    name=Typed('name',str)#用描述符定义,注意传个name 把程序写活
    age=Typed('age',int)
    def __init__(self,name2,age2):
        self.name=name2  #相当于Typed('name',str)='sxj'
        self.age=age2    #相当于Typed('age',int)='22'
p1=People('sxj','22')#赋值用set方法 
p1.name='zzz' #调用使用get方法
print(p1.name)
print(p1.__dict__)#因为name 被数据描述符代理了,有更高的优先级,self.name=name这一步触发的是代理,而不是实例,所以不在dict里面了
>>>>

set方法 <__main__.People object at 0x102097d68> sxj
set方法 <__main__.People object at 0x102097d68> 22
age没有传递<class 'int'>格式
set方法 <__main__.People object at 0x102097d68> zzz
get方法 <__main__.People object at 0x102097d68> <class '__main__.People'>
zzz
{'name': 'zzz'}



posted @ 2019-09-17 20:39  小圣庄  阅读(105)  评论(0编辑  收藏  举报