python学习之类装饰器应用和数据描述符相结合
def deco(**kwargs):
def wrapper(obj):
for key, val in kwargs.items():
setattr(obj, key, Typed(key, val))
return obj
return wrapper
class Typed:
def __init__(self, key, expected_type):
self.key = key
self.expected_type = expected_type
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('%s 传入的类型不是%s' % (self.key, self.expected_type))
instance.__dict__[self.key] = value
def __delete__(self, instance):
pass
@deco(name=str, age=int, gender=str, height=int)
class People:
def __init__(self, name, age, gender, height):
self.name = name
self.age = age
self.gender = gender
self.height = height
p1 = People('alan', 18, 'boy', 185)
print(People.__dict__)
****************************************************************
<__main__.lazyproperty object at 0x0000000002933320> 实例
<__main__.Room object at 0x0000000002933390> 实例
<class '__main__.Room'> 类
****************************************************************