• 2019年9月23日 类的装饰器的应用


    class Leixin:
        def __init__(self,k,t):#k 通过该方法将程序写活
            self.k=k
            self.t=t
    
        def __set__(self, instance, value):#从优先级考虑必须要有set方法,必须要定义成数据描述符,这样实例时候才能优先触发
            print('set方法',instance,value) #instance 就是实例本身p1,value就是赋给name的值。
            if not isinstance(value,self.t):
                print("%s没有传递%s格式"%(self.k,self.t))
                return
            instance.__dict__[self.k]=value #添加到实例到字典中
    
        def __get__(self, instance, owner):
            print('get方法',instance,owner)#owner 就是对应的类People
            return instance.__dict__[self.k] #取出实例中存储的值
    
    def deco(**kwargs):#通过函数的嵌套,达到加参数的目的kwargs={'name':str,'age':int}
        def wrapper(obj):#obj=People
            for key,val in kwargs.items():#(('name',str),('age',int))
                print(key,val)
                setattr(obj,key,Leixin(key,val))#定义描述符
               # setattr(People,'name',Leixin('name',str))
                #相当于People.name=Leixin('name',str)
            return obj
        return wrapper
    
    @deco(name=str,age=int)#@wrapper>>>People=wrapper(People)
    class People:
        def __init__(self,name,age,salary,gender,heigh):
            self.name=name
    
    p1=People('s',12,222,'man',11)
    
    print(People.__dict__)

    >>>>

    name <class 'str'>
    age <class 'int'>
    set方法 <__main__.People object at 0x100797e10> s
    {'__module__': '__main__', '__init__': <function People.__init__ at 0x10079d268>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'name': <__main__.Leixin object at 0x100797d68>, 'age': <__main__.Leixin object at 0x100797dd8>}

  • 相关阅读:
    邮票面值设计(codevs 1047) 题解
    练习 : 生成器和模块
    练习 : 数据类型之字符串
    练习 : 函数基础
    练习 : 高阶函数
    练习 : 数据类型之列表
    练习 : 数据类型之元组
    练习 : 数据类型之字典
    练习 : 分支结构和循环结构
    练习 : 变量和运算符
  • 原文地址:https://www.cnblogs.com/python1988/p/11574825.html
Copyright © 2020-2023  润新知