利用描述符自定义property
class Lazyproperty: def __init__(self,func): #传的func函数是被描述的类中的函数属性 self.func = func def __get__(self, instance, owner): #instance 是实例 if instance is None: return self #当没有实例时返回自身Lazyproperty() res = self.func(instance) #func是被描述的函数,就相当于运行area这个函数 setattr(instance,self.func.__name__,res) #将结果添加到实例字典中,但要注意,当是数据描述符时,还是从数据描述符中查找 return res class Room: def __init__(self,name,width,length): self.name =name self.width = width self.length = length @Lazyproperty #area = Lazyproperty(area) 调用描述符 def area(self): return self.width * self.length r1 = Room("客厅",20,30) print(Room.__dict__) print(r1.area) print(Room.area) #类调用静态属性时,instance实例对象是不存在的,返回时None
#property:实质实现的get,set,del
class Foo: @property def test(self): print("get时运行") @test.setter #只有定义了property这个静态属性,才能设置setter def test(self, val): print("set时运行", val) @test.deleter def test(self): print("deleter时运行") def get_aaa(self): print("get时运行") def set_aaa(self,val): print("set时运行",val) def del_aaa(self): print("del时运行") aaa = property(get_aaa,set_aaa,del_aaa) #这种等同上面的属性操作 f1 =Foo() f1.test f1.test="tt" f1.aaa = "ss"