自定制property

时间:2023-03-09 00:15:02
自定制property
class Lazyproperty:
def __init__(self, func):
self.func = func def __get__(self, instance, owner):
print('get')
# print(instance)
# print(owner)
if instance is None:
return self res = self.func(instance)
setattr(instance, self.func.__name__, res)
return res class Room:
def __init__(self, width, length):
self.width = width
self.length = length @Lazyproperty
def area(self):
return self.width * self.length @property
def area1(self):
return self.width * self.length r = Room(1, 2) # print(Room.area) print(r.area1) print(r.area)
print(r.__dict__)
print(r.area)