类的装饰器应用

def Typed(**kwargs):
    def deco(obj):
        for key,val in kwargs.items():
            # obj.key=val
            setattr(obj,key,val)
        return obj
    return deco

@Typed(x=1,y=2,z=3)   #1.Typed(x=1,y=2,z=3) --->deco   2.@deco---->Foo=deco(Foo)
class Foo:
    pass
print(Foo.__dict__)

# @Typed(name='egon')  #@deco   ---->Bar=deco(Bar)
# class Bar:
#     pass
# print(Bar.name)

'''
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2, 'z': 3}

进程已结束,退出代码0
'''

class Typed:
    def __init__(self,key,expected_type):
        self.key=key
        self.expected_type=expected_type
    def __get__(self, instance, owner):
        print('get方法')
        # print('instance参数【%s】' %instance)
        # print('owner参数【%s】' %owner)
        return instance.__dict__[self.key]
    def __set__(self, instance, value):
        print('set方法')
        # print('instance参数【%s】' % instance)
        # print('value参数【%s】' % value)
        # print('====>',self)
        if not isinstance(value,self.expected_type):
            # print('你传入的类型不是字符串,错误')
            # return
            raise TypeError('%s 传入的类型不是%s' %(self.key,self.expected_type))
        instance.__dict__[self.key]=value
    def __delete__(self, instance):
        print('delete方法')
        # print('instance参数【%s】' % instance)
        instance.__dict__.pop(self.key)

def deco(**kwargs): #kwargs={'name':str,'age':int}
    def wrapper(obj): #obj=People
        for key,val in kwargs.items():#(('name',str),('age',int))
            setattr(obj,key,Typed(key,val))
            # setattr(People,'name',Typed('name',str)) #People.name=Typed('name',str)
        return obj
    return wrapper
@deco(name=str,age=int)  #@wrapper ===>People=wrapper(People)
class People:
    name='alex'
    # name=Typed('name',str)
    # age=Typed('age',int)
    def __init__(self,name,age,salary,gender,heigth):
        self.name=name
        self.age=age
        self.salary=salary
# p1=People('213',13.3,13.3,'x','y')
print(People.__dict__)

'''
D:\py\venv\Scripts\python.exe D:/pycode/21/day21_lesson/test.py
{'__module__': '__main__', 'name': <__main__.Typed object at 0x00000000027CE860>, '__init__': <function People.__init__ at 0x00000000027D58C8>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'age': <__main__.Typed object at 0x00000000027CED30>}

进程已结束,退出代码0

'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值