描述符:定义__get__,__set__,__del__的新式类,并在另一个中被代理使用
类装饰器: 传入一个函数名作为参数,再返回函数名,也是一种特殊的高阶函数
应用场景:比如要动态传入参数,并自定义参数的类型,可以检测期望的参数类型,比如人名应该是字符串类型,年了应该是整数型:
eg:
class Typed: def __init__(self,name,expected_type): self.name=name self.expected_type=expected_type def __get__(self, instance, owner): print('get拿数据') def __set__(self, instance, value): if not isinstance(value,self.expected_type): #检查变量类型 raise TypeError('%s不是%s类型' %(instance,self.expected_type)) else: setattr(self,self.name,value) def deco(**kwargs): def wrapper(obj): for key,val in kwargs.items(): setattr(obj,key,Typed(key,val)) return obj return wrapper @deco(name=str,age=int) #People=wrapper(People) class People: def __init__(self,name,age): self.name=name self.age=age p1=People('sla',88) print(People.__dict__)