本文实例讲述了Python高级属性属性用法。分享给大家供大家参考,具体如下:
<强> 1。产权属性:强>
是一个提高开发者用户体验度的属性,可以将一个函数改造的像属性一样。
例:
#定义的时候像是一个函数使用的时候和属性的方式是以样的 类Foo(对象): @ property def钱(自我): 返回100 # f=Foo () # m=f.money () #打印(m) f=Foo () 打印(f.money) >之前执行结果:
<强> 2.属性简单应用:强>
例:根据当前页数和每页显示数据条数,计算出该页起始编号和结尾编号
类寻呼机: def __init__(自我,current_page): #用户当前请求的页码(第一页,第二页……) 自我。current_page=current_page #每页默认显示100条数据 自我。per_items=100 @ property def开始(自我): val=(自我。current_page - 1) *自我。per_items + 1 返回瓦尔 @ property def结束(自我): val=自我。current_page * self.per_items 返回瓦尔 p=寻呼机(2) 打印(p.start) 打印(p.end) >之前执行结果:
<强> 3。装饰器方式:在方法上应用装饰器强>
三种@ property装饰器:
类商品: @ property def价格(自我): print (@ property) @price.setter def价格(自我价值): print (@price.setter) @price.deleter def价格(自我): print (@price.deleter) # # # # # # # # # # # # # # # #调用# # # # # # # # # # # # # # # obj=货物() obj。价格#自动执行@ property修饰的价格方法,并获取方法的返回值 obj。价格=123 #自动执行@price。setter修饰的价格方法,并将123年赋值给方法的参数 德尔obj。价格#自动执行@price.deleter修饰的价格方法 >之前 例:
类产品(对象): def __init__(自我): self.org_price=1000 #价格 自我。折扣=0.7 #折扣 @ property def价格(自我): val=self.org_price * self.discount #返回价格*折扣 返回瓦尔 @price.setter def价格(自我,new_val): #接收val,将价格修改为瓦尔 self.org_price=new_val @price.deleter def价格(自我): #将折扣修改为1(删掉折扣) 自我。折扣=1 g=货物() 打印(g.price) g。价格=2000 打印(g.price) 德尔g.price 打印(g.price) >之前执行结果:
<>强4。类属性方式:在类中定义值为财产对象的类属性强>
属性名=属性(获取,修改,删除,备注)
例:
类产品(对象): def __init__(自我): self.org_price=1000 #价格 自我。折扣=0.7 #折扣 def get_price(自我): val=self.org_price * self.discount #返回价格*折扣 返回瓦尔 def set_price(自我,new_val): #接收new_val,将价格修改为new_val self.org_price=new_val def del_price(自我): #将折扣修改为1(删掉折扣) 自我。折扣=1 价格=属性(get_price set_price del_price,“备注:价格”) g=货物() 打印(g.price) #获取商品价格 g。价格=2000 #修改商品价格 打印(g.price) 德尔·g。价格#删除商品折扣 打印(g.price) 打印(Goods.price.__doc__) >之前执行结果:
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》,《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
Python高级属性属性用法实例分析