zoukankan      html  css  js  c++  java
  • 类的装饰器

    一、与函数的装饰器一样,类也可以被装饰

    def deco(func):
        print('=============>')
        return func
    
    @deco    #test = deco(test)
    def test():
        print('test函数')
    
    test()
    

    在装饰器给类设置属性

    def deco(obj):
        print('=============>')
        obj.x = 1
        obj.y = 2
        obj.z = 3
        return obj
    
    @deco    #test = deco(test)
    def test():
        print('test函数')
    
    print(test.__dict__)
    

      

    上述代码在装饰器函数中把属性写死了,如果不同的类需要设置不同的属性呢

    def deco(**kwargs):
        def wrapper(obj):
            for key,val in kwargs.items():
                setattr(obj,key,val)
            return obj
        return wrapper
    
    @deco(x = 1,y = 2, z = 3)  #1.deco(x= 1,y= 2,z=3) --->wrapper 2.Foo = wrapper(Foo)
    class Foo:
        pass
    
    print(Foo.__dict__)
    
    @deco(name= 'jinling')
    class Bar:
        pass
    print(Bar.name)
    print(Bar.__dict__)
    

    与前面描述符应用结合,类的装饰器的应用

    class Typed:
        def __init__(self,key,excp_typed):
            self.key = key
            self.excp_typed = excp_typed
        def __get__(self, instance, owner):
            print('正在执行get方法')
            return instance.__dict__[self.key]
        def __set__(self, instance, value):
            print('正在执行set方法')
            if not isinstance(value,self.excp_typed):
                raise TypeError("你传入的参数类型不是",self.excp_typed)
            instance.__dict__[self.key] = value
        def __delete__(self, instance):
            print("正在执行delete方法")
            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))
                print("=====>")
                setattr(obj, key,Typed(key,val))  #People.name = Type('name',str)
    
            return obj
        return wrapper
    @deco(name = str, age = int)   #@wrapper ==>People = wrapper(People)
    class People:
        def __init__(self,name,age,salary):
            self.name = name
            self.age = age
            self.salary = salary
    
    p1 = People('jinling',19,13000)
    print(p1.__dict__)
    

      

      

     

    一个奋斗中的产品小白
  • 相关阅读:
    kettle参数、变量详细讲解[转]
    C# 异步
    〖Python〗-- 模块与包
    〖Python〗-- 异常处理
    〖Python〗-- 面向对象进阶
    〖Python〗-- 反射、内置attr、包装
    〖Python〗-- property、静态方法、类方法
    〖Python〗-- 面向对象编程的继承、多态与多态性、封装
    〖Python〗-- 面向对象编程、继承、组合、接口和抽象类
    〖Python〗-- 递归、面向对象初识及编程思想
  • 原文地址:https://www.cnblogs.com/dabai123/p/11666055.html
Copyright © 2011-2022 走看看