python学习之描述符自制property
2021-01-17 19:16
标签:Owner pre int 自制 python 实例 property get ini python学习之描述符自制property 标签:Owner pre int 自制 python 实例 property get ini 原文地址:https://www.cnblogs.com/jinpingzhao/p/12916330.htmlclass lazyproperty:
def __init__(self,fun):
self.fun=fun
def __get__(self, instance, owner):
print("get")
print(‘===========>‘,self)
print(‘===========>‘,instance)
print(‘===========>‘,owner)
if instance is None:
return self
res=self.fun(instance)
setattr(instance,self.fun.__name__,res)
return res
class Room:
#area1=lazyproperty(area1)
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
def area1(self):
return self.width*self.length
r1=Room("卧室",6,5)
# print(Room.__dict__)
# print(r1.area) #实例调用
print(r1.area1)
# print(Room.area) #类调用
# print(Room.area1)
print(r1.area1)
print(r1.area1)
文章标题:python学习之描述符自制property
文章链接:http://soscw.com/index.php/essay/43333.html