python3中property使用方法详解
2019-04-24 07:01
681 查看
本文实例为大家分享了python3中的property使用方法,供大家参考,具体内容如下
property属性
定义
一个可以使实例方法用起来像实例属性一样的特殊关键字,可以对应于某个方法,通过使用property属性,能够简化调用者在获取数据的流程(使代码更加简明)。
property属性的定义和调用要注意以下几点:
调用时,无需括号,加上就错了;并且仅有一个self参数
实现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取代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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- Python中property函数用法实例分析
- Python中property属性实例解析
- python @property的用法及含义全面解析
- Python解析json之ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)
- 实例讲解Python编程中@property装饰器的用法
- Python黑魔法@property装饰器的使用技巧解析
- Python Property属性的2种用法
- 介绍Python的@property装饰器的用法
- Python中用Descriptor实现类级属性(Property)详解
- python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
相关文章推荐
- 详解Python中for循环的使用方法
- python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
- python MethodType方法详解和使用
- 举例详解Python中的split()函数的使用方法
- 详解Python的Django框架中Manager方法的使用
- 详解python中的json的基本使用方法
- Python使用pylab库实现画线功能的方法详解
- 详解Python中for循环的使用方法
- 详解Python中的strftime()方法的使用
- 详解使用Python处理文件目录的相关方法
- 详解Python中使用base64模块来处理base64编码的方法
- python学习笔记 --- python中使用哈希方法处理字符与数字,ord()等函数详解
- Python标准库:内置函数hasattr() getattr() setattr() 函数使用方法详解
- python中的sort方法使用详解
- python中的sort方法使用详解
- 详解Python中find()方法的使用
- 详解Python中expandtabs()方法的使用
- 详解Python中time()方法的使用的教程
- 详解Python的Django框架中Manager方法的使用
- 详解使用Nginx和uWSGI配置Python的web项目的方法