欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

property自己实现

程序员文章站 2023-11-13 13:44:52
# 先回顾一下 class Room: def __init__(self,name,width,length): self.name = name self.width = width self.length = length @property def area(self): return se... ......
# 先回顾一下
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
r1 = room('wang',100,100)
print(r1.area)

class lazyproperty:
    def __init__(self,func):
        self.func = func
    def __get__(self,instance,owner):
        print("我们自己定义的属性")
        if instance is none:
            return self
        return self.func(instance)
class room:
    def __init__(self,name,width,length):
        self.name = name
        self.width = width
        self.length = length
    @lazyproperty
    # area = lazyproperty(area)
    # 现在area是一个类,而不是函数
    def area(self):
        # print(self.area)
        return self.width * self.length
r1=room('alex',1,1)
print(r1.area)