自定制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)

 

posted @ 2019-01-11 16:25  我爱敲代码  阅读(102)  评论(0编辑  收藏  举报