类的装饰器

装饰可以是一个函数
class Type:
    def __init__(self,key,type):
        self.key=key
        self.type=type
    def __get__(self, instance, owner):
        pass
        return instance.__dict__[self.key]
    def __set__(self, instance, value):
        if not isinstance(value,self.type):
            raise TypeError('%s不是%s'%(value,self.type))
        else:
            instance.__dict__[self.key]=value
    def __delete__(self, instance):
        pass

def deco(**kwargs):
    def wrapper(obj):
        for key,val in kwargs.items():
            setattr(obj,key,Type(key,val))
        return obj
    return wrapper

@deco(name=str,age=int,salary=float)#@wrapper ===>People=wrapper(People)
class People:
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary
p1=People("alex",18,3000.0)
print(p1.__dict__)
#p2=People('bart','18',3000)

也可以是一个类

自定制property

class Lazyproperty:
    def __init__(self,func):
        print('=====>')
        self.func=func
    def __get__(self, instance, owner):
        print('get')
        if instance is None:#当类访问静态属性时instance为None
            return self
        res= self.func(instance)
        instance.__dict__[self.func.__name__]=res  #将areal直接加进实例字典
        return res


class Room:
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length

    @property
    def area(self):
        return self.width*self.length

    @Lazyproperty   #areal=Lazyproperty(areal)
    def areal(self):
        return self.width*self.length

r=Room('bath',10,20)
print(r.area)
print(r.areal)
print(r.__dict__) #有属性areal但是没有area
print(Room.area,Room.areal)

#输出
#=====>
#200
#get
#200
#{'name': 'bath', 'width': 10, 'length': 20, 'areal': 200}
#get
#<property object at 0x000001BEA6466778> <__main__.Lazyproperty object at 0x000001BEA66FA208>

property补充

class Student:
    def __init__(self,name,age,score):
        self.name=name
        self.age=age
        self.__score=score
    @property       #不可传入参数
    def score(self):
        return self.__score
    @score.setter
    def score(self,value):  #可以传入参数
        if not isinstance(value,float):
            raise ValueError('请输入正确成绩')
        self.__score=value
    @score.deleter
    def score(self):
        print('delete score')
        del self.__score


a=Student('alex',18,90.0)
print(a.score)
a.score=95.0
print(a.score)
del a.score
print(a.__dict__)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值