Python高级property属性用法实例分析

桃夭
桃夭
发布时间:2026-10-13 | 3人浏览过
原创

本文深入解析Python中property属性的三种实现方式:基础装饰器用法、@property/setter/deleter组合以及类属性直接定义。通过分页计算、商品价格管理等实际案例,展示如何将函数调用转化为属性访问,提升代码可读性与用户体验。

Python property属性概述

本文详细介绍Python中高级property属性的具体用法,旨在帮助开发者深入理解并掌握这一特性,供参考学习。

property属性概述

1. property属性的核心概念:

该属性旨在提升开发者的使用体验,其核心功能是将一个普通函数转换为类似属性的访问方式,使得调用更加直观。

示例代码:


# 定义的时候像是一个函数 使用的时候和属性的方式是以样的
class Foo(object):
  @property
  def money(self):
    return 100
# f = Foo()
# m = f.money()
# print(m)
f = Foo()
print(f.money)

运行结果如下:

property的基础应用场景

2. property的基础应用场景:

示例:根据当前页码和每页显示的数据条数,计算并返回该页数据的起始编号和结束编号。


class Pager:
  def __init__(self, current_page):
    # 用户当前请求的页码(第一页、第二页...)
    self.current_page = current_page
    # 每页默认显示100条数据
    self.per_items = 100
  @property
  def start(self):
    val = (self.current_page - 1) * self.per_items + 1
    return val
  @property
  def end(self):
    val = self.current_page * self.per_items
    return val
p = Pager(2)
print(p.start)
print(p.end)

运行结果如下:

使用装饰器实现property

3. 使用装饰器实现:在方法上应用@property装饰器

主要涉及三种@property相关的装饰器用法:


class Goods:
  @property
  def price(self):
    print('@property')
  @price.setter
  def price(self, value):
    print('@price.setter')
  @price.deleter
  def price(self):
    print('@price.deleter')
# ############### 调用 ###############
obj = Goods()
obj.price     # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
obj.price = 123  # 自动执行 @price.setter 修饰的 price 方法,并将 123 赋值给方法的参数
del obj.price   # 自动执行 @price.deleter 修饰的 price 方法

示例代码:


class Goods(object):
  def __init__(self):
    self.org_price = 1000 # 价格
    self.discount = 0.7 # 折扣
  @property
  def price(self):
    val = self.org_price * self.discount
    # 返回价格*折扣
    return val
  @price.setter
  def price(self, new_val):
    # 接收val,将价格修改为val
    self.org_price = new_val
  @price.deleter
  def price(self):
    # 将折扣修改为1(删掉折扣)
    self.discount = 1
g = Goods()
print(g.price)
g.price = 2000
print(g.price)
del g.price
print(g.price)

运行结果如下:

类属性方式定义property

4. 类属性方式实现:在类中直接定义值为property对象的类属性

语法格式为:属性名 = property(获取方法, 修改方法, 删除方法, 备注信息)

示例代码:


class Goods(object):
  def __init__(self):
    self.org_price = 1000 # 价格
    self.discount = 0.7 # 折扣
  def get_price(self):
    val = self.org_price * self.discount
    # 返回价格*折扣
    return val
  def set_price(self, new_val):
    # 接收new_val,将价格修改为new_val
    self.org_price = new_val
  def del_price(self):
    # 将折扣修改为1(删掉折扣)
    self.discount = 1
  price = property(get_price, set_price, del_price, "备注:价格")
g = Goods()
print(g.price) # 获取商品价格
g.price = 2000 # 修改商品价格
print(g.price) 
del g.price # 删除商品折扣
print(g.price)
print(Goods.price.__doc__)

运行结果如下:

如果您对Python其他高级特性感兴趣,建议查阅本站相关专题,包括《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》以及《Python入门与进阶经典教程》。

希望上述关于Python property属性的解析与实例,能对您的Python程序设计工作提供切实帮助。

相关标签:

本站声明

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

Python 相关产品和应用

全部下载

专题列表