python 25 类装饰器

我是研究僧i 提交于 2020-03-10 14:46:19
# 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'>)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!