描述符的应用

 1 class Typed:
 2     def __init__(self,key,expected_type):
 3         self.key=key
 4         self.expected_type=expected_type
 5     def __get__(self, instance, owner):
 6         print('get方法')
 7         return instance.__dict__[self.key]
 8     def __set__(self, instance, value):
 9         print('set方法')
10         if not isinstance(value,self.expected_type):
11             raise TypeError('%s 传入的类型不是%s' %(self.key,self.expected_type))
12         instance.__dict__[self.key]=value
13     def __delete__(self, instance):
14         print('delete方法')
15         instance.__dict__.pop(self.key)
16 
17 class People:
18     name=Typed('name',str) #t1.__set__()  self.__set__()
19     age=Typed('age',int) #t1.__set__()  self.__set__()
20     def __init__(self,name,age,salary):
21         self.name=name
22         self.age=age
23         self.salary=salary
24 
25 # p1=People('alex','13',13.3)
26 p1=People(213,13,13.3)

 

posted on 2019-02-24 22:27  元神出窍  阅读(85)  评论(0编辑  收藏  举报

导航