利用描述符自定制property

property 即静态方法

class Lazyproperty:
    def __init__(self,func):
        self.func = func
    def __get__(self, instance, owner):
        print('正在执行get方法')
        if instance is None:
            return self
        res = self.func(instance)
        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
    @property   #自带的property方法
    def area1(self):
        return self.width * self.length


r1 = Room('jinling',10,10)
print(r1.area)
print(Room.area1)
print(Room.area)

property补充

class Foo:
    @property
    def AAA(self):
        print('get的时候运行')
    @AAA.setter
    def AAA(self,val):
        print('set的时候运行我啊',val)
    @AAA.deleter
    def AAA(self):
        print('del的时候运行我啊')

#只有在属性AAA定义property后才能定义AAA.setter, AAA.delete
f1 = Foo()
f1.AAA
f1.AAA = 'jinling'
del f1.AAA

 

另一种用法

class Foo:

    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.AAA
f1.AAA = 'jinling'
del f1.AAA

  

 

 

posted @ 2019-10-13 22:52  绝世刘  阅读(124)  评论(0编辑  收藏  举报