博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
属性的两种定义方式
阅读量:4323 次
发布时间:2019-06-06

本文共 1211 字,大约阅读时间需要 4 分钟。

装饰器方式:在类的普通方法上应用@property装饰器

经典类,具有一种@property装饰器(如上一步实例)
# ############### 定义 ###############    class Goods:    @property    def price(self): return "wupeiqi" # ############### 调用 ############### obj = Goods() result = obj.price # 自动执行 @property 修饰的 price 方法,并获取方法的返回值 新式类,具有三种@property装饰器
# ############### 定义 ###############class Goods(object):    @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.original_price = 100 # 折扣 self.discount = 0.8 @property def price(self): # 实际价格 = 原价 * 折扣 new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deltter def price(self, value): del self.original_price obj = Goods() obj.price # 获取商品价格 obj.price = 200 # 修改商品原价 del obj.price # 删除商品原价
 

转载于:https://www.cnblogs.com/stonerainjc/p/6821643.html

你可能感兴趣的文章
原型模式
查看>>
Hadoop RPC源码阅读-交互协议
查看>>
WASAPI、DirectSound/DS、WaveOut、Kernel Streaming/KS
查看>>
Perl按行分割文件
查看>>
根据现有表操作基于active record的model
查看>>
NotMapped属性特性
查看>>
Count and Say
查看>>
GridView数据导入Excel/Excel数据读入GridView
查看>>
566. Reshape the Matrix
查看>>
python数据结构与算法之搜索
查看>>
(最小点覆盖) poj 2226
查看>>
(树形DP) poj 3659
查看>>
获取类的属性名和值
查看>>
python对json的操作总结
查看>>
学习进度表第十一周
查看>>
js屏蔽回车键
查看>>
Memcached通用类(基于enyim.com Memcached Client)
查看>>
c#组元(Tuple)的使用
查看>>
【NO.66】转 Yahoo的军规条例
查看>>
vim基础学习之搜索功能
查看>>