装饰器--@property

以下内容引用于:https://www.jb51.net/article/134148.htm

 

不用@property,代码如下:

class Rectangle:

    def __init__(self):
        self.width = 10
        self.height = 20

r = Rectangle()
print(r.width)

r.width = 15
print(r.width)

结果:

10

15

 

装饰器@property使方法像属性一样调用,就像是一种特殊的属性

使用@property,代码如下:

class Rectangle:
        
    def __init__(self):
        self.true_width = 10
        self.true_height = 20
                
    @property
    def width(self):
        return self.true_width
        
    @property
    def height(self):
        return self.true_height

r = Rectangle()
print(r.width)

r.width = 15
print(r.width)

结果,使用property后不能再随意修改类内部的属性值:

10
Traceback (most recent call last):
  File "./property.py", line 28, in <module>
    r.width = 15
AttributeError: can't set attribute

 

使用@property后要修改属性值,则代码如下:

class Rectangle:
        
    def __init__(self):
        self.true_width = 10
        self.true_height = 20
                
    @property
    def width(self):
        return self.true_width
        
    @property
    def height(self):
        return self.true_height
                
    @width.setter
    def set_width(self, input_width):
        self.true_width = input_width
        return self.true_width
        
    @height.setter
    def set_height(self, input_height):
        self.true_height = input_height
        return self.ture_height

r = Rectangle()
print(r.width)

r.set_width = 15
print(r.width)

结果如下:

10

15

posted on 2019-04-17 22:15  苦海舟  阅读(74)  评论(0)    收藏  举报

导航