Python中@property装饰器的用法与原理详解

星野
星野
发布时间:2026-10-15 | 2人浏览过
原创

本文详细解析Python中@property装饰器的使用方法。通过装饰器方式和类属性方式两种途径,实现将方法调用转化为属性访问,简化数据获取流程并防止外部直接赋值。文章对比了传统getter/setter与@property的优势,展示了如何封装复杂逻辑及控制属性访问权限。

1.什么是@property

简单来说,当类中的某个方法被@property装饰器修饰后,该方法就可以像访问普通属性一样被调用。这种机制简化了调用者获取数据的流程,同时避免了将内部属性直接暴露给外部,防止使用者进行不合理的赋值操作。需要注意以下两点关键特性:

  • 调用被@property装饰的方法时,不需要添加括号。
  • 该方法在定义时,只能包含self这一个参数。
>>> class Goods():
        def __init__(self,unit_price,weight):
            self.unit_price = unit_price
            self.weight = weight
        @property
        def price(self):
            return self.unit_price * self.weight
>>> lemons = Goods(7,4)
>>>
>>> lemons.price
28

上述示例通过直接调用属性名称的方式,实际上触发了price方法。@property将复杂的处理逻辑封装在方法内部,在取值时只需调用对应的方法名即可获取结果。

2.定义@property属性的两种方式

A、使用装饰器方式

即在类的方法上直接应用@property装饰器,如前文所示。

B、使用类属性方式

通过创建一个实例对象,并将其赋值给类属性的方式来实现。

>>> class Lemons():
        def __init__(self,unit_price=7):
            self.unit_price = unit_price
        def get_unit_price(self):
            return self.unit_price
        def set_unit_price(self,new_unit_price):
            self.unit_price = new_unit_price
        def del_unit_price(self):
            del self.unit_price
        x = property(get_unit_price, set_unit_price, del_unit_price)
>>> fruit = Lemons()
>>> 
>>> fruit.x                         #调用 fruit.x 触发 get_unit_price
7
>>> 
>>> fruit.x = 9                     #调用 fruit.x = 9 触发 set_unit_price
>>> 
>>> fruit.x
9
>>> 
>>> fruit.unit_price                #调用 fruit.unit_price 触发 get_unit_price
9
>>> del fruit.x                     #调用 del fruit.x 触发 del_unit_price 
>>> 
>>> fruit.unit_price
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    l.unit_price
AttributeError: 'Lemons' object has no attribute 'unit_price'

property方法可以接收四个参数,具体功能如下:

  • 第一个参数是获取属性的方法名,当执行对象.属性操作时会自动触发该方法。
  • 第二个参数是设置属性的方法名,当对属性进行赋值时会自动触发该方法。
  • 第三个参数是删除属性的方法名,当执行删除属性操作时会自动触发该方法。
  • 第四个参数是字符串类型的描述文档,当调用对象.属性.__doc__时会返回该描述信息。

3.使用@property替代传统的getter和setter方法

>>>class Watermelon():
       def __init__(self,price):
           self._price = price                  #私有属性,外部无法修改和访问
 
       def get_price(self):
           return self._price
 
       def set_price(self,new_price):
           if new_price > 0:
               self._price = new_price
           else:
               raise 'error:价格必须大于零'

通过@property装饰器可以替代传统的getter和setter方法,使代码更加简洁。

>>>class Watermelon():
       def __init__(self,price):
           self._price = price
       @property                          #使用@property装饰price方法
       def price(self):
           return self._price
       @price.setter                      #使用@property装饰方法,当对price赋值时,调用装饰方法
       def price(self,new_price):
           if new_price > 0:
               self._price = new_price
           else:
               raise 'error:价格必须大于零'
>>> watermelon = Watermelon(4)
>>> 
>>> watermelon.price
4
>>> 
>>> watermelon.price = 7
>>> 
>>> watermelon.price
7

至此,关于Python中@property用法的介绍已完成。如需了解更多相关内容,请查阅本站过往文章或继续浏览后续教程,感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表