使用类的装饰器完成:在类实例化对象时,对实例化参数的类型进行限制。
1 #Author : Kelvin
2 #Date : 2019/1/24 20:57
3
4 #控制类的实例化对象时的参数值
5
6 #定义描述符
7 class Type():
8 def __init__(self,key,type):
9 self.key=key
10 self.type=type
11 def __get__(self, instance, owner):
12 # print("get")
13 return instance.__dict__[self.key]
14 def __set__(self, instance, value):
15 # print("set")
16 if not isinstance(value,self.type):
17 raise TypeError("%s Type is not %s"%(self.key,self.type))
18 instance.__dict__[self.key]=value
19 def __delete__(self, instance):
20 # print("delete")
21 instance.__dict__.pop(self.key)
22
23
24 #定义装饰器
25 def deco(*args,**kwargs):
26 def wrapper(obj):
27 for k,v in kwargs.items():
28 setattr(obj,k,Type(k,v))
29 return obj
30 return wrapper
31
32
33 #定义类
34 @deco(name=str,age=int,salary=float)
35 class People:
36 def __init__(self,name,age,salary):
37 self.name=name
38 self.age=age
39 self.salary=salary
40 p1=People("kelvin",18,12800.36)