类的装饰器应用

 1 class Type:
 2     def __init__(self, key, expcet_type):
 3         self.key = key
 4         self.expct_type = expcet_type
 5 
 6     def __get__(self, instance, owner):
 7         print('执行get')
 8         return instance.__dict__[self.key]
 9 
10     def __set__(self, instance, value):
11         print('执行set')
12         if not isinstance(self.key, self.expct_type):
13             print('%s 类型不符合%s'%(value,self.expct_type))
14             return
15         instance.__dict__[self.key] = value
16 
17 
18 def test(**kwargs):
19     def wrapper(obj):
20         for k, v in kwargs.items():
21             val = Type(k, v)
22             setattr(obj, k, val)
23         return obj
24 
25     return wrapper
26 
27 
28 @test(name=str, age=int, gender=str, price=int)
29 class Foo:
30     def __init__(self, name, age, gender, price):
31         self.name = name
32         self.age = age
33         self.gender = gender
34         self.price = price
35 
36 
37 print(Foo.__dict__)
38 f1 = Foo('alex',16, '',13)
39 print(f1.__dict__)
40 输出:
41 {'__module__': '__main__', '__init__': <function Foo.__init__ at 0x009A8A00>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'name': <__main__.Type object at 0x00992FD0>, 'age': <__main__.Type object at 0x009AE148>, 'gender': <__main__.Type object at 0x009AE0E8>, 'price': <__main__.Type object at 0x009AE178>}
42 执行set
43 执行set
44 16 类型不符合<class 'int'>
45 执行set
46 执行set
47 13 类型不符合<class 'int'>
48 {'name': 'alex', 'gender': ''}

 

posted @ 2020-03-16 10:32  竹石2020  阅读(150)  评论(0编辑  收藏  举报