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 class People: 25 name=Type("name",str) 26 age=Type("age",int) 27 salary=Type("salary",float) 28 def __init__(self,name,age,salary): 29 self.name=name 30 self.age=age 31 self.salary=salary 32 p1=People("kelvin",18,12800.36)
此时如果实例化对象时,传入的参数不符合条件就会抛出异常!
原文地址:https://www.cnblogs.com/sun-10387834/p/10316860.html
时间: 2024-11-09 05:48:16