Python3中property属性详解:装饰器与类方法两种实现方式
本文详细解析Python3中property属性的两种实现方式:使用@property装饰器和property()类方法。通过具体代码示例,演示如何简化数据访问流程,实现私有属性的安全读写与删除,提升代码简洁性与可维护性。
本文详细介绍Python3中property属性的使用方法,供读者参考学习。
property属性概述
property属性概述
基本概念
property是一个特殊关键字,允许将实例方法伪装为实例属性。它绑定到某个方法上,通过property属性可以简化调用者获取数据的流程,使代码更加简洁明了。
使用property属性时需注意以下要点:
调用时不需要加括号,若加上括号则会导致错误;同时该方法仅接受self这一个参数。
property属性的两种实现方式
实现property属性主要有两种方式:
使用装饰器实现
方式一:使用装饰器
在新式类中,属性有三种访问方式,分别对应三个特定的装饰器:
- @property用于实现读取操作
- @方法名.setter用于实现修改操作
- @方法名.deleter用于实现删除操作
class Goods:
def __init__(self):
self.age = 18
@property
def price(self): # 读取
return self.age
# 方法名.setter
@price.setter # 设置,仅可接收除self外的一个参数
def price(self, value):
self.age = value
# 方法名.deleter
@price.deleter # 删除
def price(self):
del self.age
# ############### 调用 ###############
obj = Goods() # 实例化对象
obj.age # 直接获取 age属性值
obj.age= 123 # 修改age的值
del obj.age # 删除age属性的值
使用类属性实现
方式二:使用类属性
当通过类属性的方式创建property属性时,需要调用property()方法,该方法接收四个参数:
- 第一个参数是读取方法名,当访问对象.属性时自动触发执行该方法
- 第二个参数是设置方法名,当执行对象.属性 = XXX赋值操作时自动触发执行该方法
- 第三个参数是删除方法名,当执行del 对象.属性时自动触发执行该方法
- 第四个参数是字符串,用于定义对象.属性.doc时的描述信息
class Goods(object):
def __init__(self):
self.price = 100 # 原价
self.discount = 0.8 # 折扣
def get_price(self):
# 实际价格 = 原价 * 折扣
new_price = self.price * self.discount
return new_price
def set_price(self, value):
self.price = value
def del_price(self):
del self.price
# 获取 设置 删除 描述文档
PRICE = property(get_price, set_price, del_price, '价格属性描述...')
# 使用此方式设置
obj = Goods()
obj.PRICE # 获取商品价格
obj.PRICE = 200 # 修改商品原价
del obj.PRICE # 删除商品原价
property的应用场景
使用property替代传统的getter和setter方法
通过@property装饰器改进对私有属性的get和set方法,实现更优雅的封装。
class Money(object):
def __init__(self):
self.__money = 0
# 使用装饰器对money进行装饰,那么会自动添加一个叫money的属性,当调用获取money的值时,调用装饰的方法
@property
def money(self):
return self.__money
# 使用装饰器对money进行装饰,当对money设置值时,调用装饰的方法
@money.setter
def money(self, value):
if isinstance(value, int):
self.__money = value
else:
print("error:不是整型数字")
a = Money()
a.money = 100
print(a.money)
以上内容为本文的全部介绍,希望能对读者的学习有所帮助,欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









