# python 类装饰器 # /usr/sbin/py/python # -*=coding:utf8-*- def dec(obj): obj.hobby = "singing" # 添加类属性 return obj # 加任意参数 def type(**kwargs): def deco(obj): for key,val in kwargs.items(): # obj.key = val setattr(obj,key,val) return obj return deco @type(school="实验小学",address="上海") # 分析 type方法返回值是deco方法 等价于 @deco 》》 Student = deco(Student) class Student: pass print(Student.__dict__) # 利用装饰器 实现参数类型限制 class Type: def __init__(self,key,parameterType): self.key = key self.parameterType = parameterType def __get__(self, instance, owner): return instance.__dict__[self.key] def __set__(self, instance, value): if isinstance(value,self.parameterType): instance.__dict__[self.key] = value else: raise TypeError("参数类型错误",value,self.parameterType) def checkType(**kwargs): def deco(obj): for key,val in kwargs.items(): setattr(obj,key,Type(key,val)) return obj return deco @checkType(name=str,age=int,salary=float) class Teacher: def __init__(self,name,age,salary): self.name = name self.age = age self.salary = salary print(Teacher.__dict__) # 'name': <__main__.Type object at 0x0397A3E8>, # 'age': <__main__.Type object at 0x0397A418>, 'salary': <__main__.Type object at 0x0397A448> # 参数被赋予了描述符 t1 = Teacher("jake",34,99.9) print(t1.__dict__) # {'name': 'jake', 'age': 34, 'salary': 99.9} t2 = Teacher("tom","error",90) # 报错 print(t2.__dict__) # File "D:/pythonProject/methodPy/test15.py", line 39, in __set__ # raise TypeError("参数类型错误",value,self.parameterType) # TypeError: ('参数类型错误', 'error', <class 'int'>)
来源:CSDN
作者:XiaoqiangNan
链接:https://blog.csdn.net/XiaoqiangNan/article/details/104770206