Python中關(guān)于property使用的小技巧
property屬性
一種用起來(lái)像是使用實(shí)例屬性一樣的特殊屬性,可以對(duì)應(yīng)于某個(gè)方法
既要保護(hù)類(lèi)的封裝特性,又要讓開(kāi)發(fā)者可以使用 對(duì)象.屬性 的方式操作方法,@property 裝飾器,可以直接通過(guò)方法名來(lái)訪(fǎng)問(wèn)方法,不需要在方法名后添加一對(duì) () 小括號(hào)。
來(lái)看下求圓的面積的例子
class Circle(object):
PI = 3.14
def __init__(self, r):
# r圓的半徑
self.r = r
self.__area = self.PI * self.r * self.r
@property
def area(self):
return self.__area
def get_area(self):
return self.__area
In [2]: c = Circle(10)
In [3]: c.area
Out[3]: 314.0
In [4]: c.get_area()
Out[4]: 314.0
property屬性的定義和調(diào)用要注意一下幾點(diǎn):
- 定義時(shí),在實(shí)例方法的基礎(chǔ)上添加
@property裝飾器;并且僅有一個(gè)self參數(shù) - 調(diào)用時(shí),無(wú)需括號(hào)
()
實(shí)例方法:c.get_area() property裝飾的方法:c.area
具體實(shí)例
對(duì)于某商城中顯示電腦主機(jī)的列表頁(yè)面,每次請(qǐng)求不可能把數(shù)據(jù)庫(kù)中的所有內(nèi)容都顯示到頁(yè)面上,而是通過(guò)分頁(yè)的功能局部顯示,所以在向數(shù)據(jù)庫(kù)中請(qǐng)求數(shù)據(jù)時(shí)就要顯示的指定獲取從第 m 條到第 n條的所有數(shù)據(jù) 這個(gè)分頁(yè)的功能包括:
- 根據(jù)用戶(hù)請(qǐng)求的當(dāng)前頁(yè)和總數(shù)據(jù)條數(shù)計(jì)算出 m 和 n
- 根據(jù) m 和 n 去數(shù)據(jù)庫(kù)中請(qǐng)求數(shù)據(jù)
class Pager(object):
def __init__(self, current_page):
# 用戶(hù)當(dāng)前請(qǐng)求的頁(yè)碼(第一頁(yè)、第二頁(yè)...)
self.current_page = current_page
# 每頁(yè)默認(rèn)顯示10條數(shù)據(jù)
self.per_items = 10
@property
def start(self):
val = (self.current_page - 1) * self.per_items
return val
@property
def end(self):
val = self.current_page * self.per_items
return val
# ipython測(cè)驗(yàn)
In [2]: p = Pager(1)
In [3]: p.start # 就是起始值,即:m
Out[3]: 0
In [4]: p.end # 就是結(jié)束值,即:n
Out[4]: 10
In [5]: p = Pager(2)
In [6]: p.start
Out[6]: 10
In [7]: p.end
Out[7]: 20
property屬性的有兩種方式
- 裝飾器 即:在方法上應(yīng)用裝飾器
@property - 類(lèi)屬性 即:在類(lèi)中定義值為
property對(duì)象的類(lèi)屬性property()
裝飾器方式
在類(lèi)的實(shí)例方法上應(yīng)用 @property 裝飾器
Python中的類(lèi)有舊式類(lèi) 和 新式類(lèi),新式類(lèi) 的屬性比 舊式類(lèi)的屬性豐富。
舊式類(lèi)
舊式類(lèi),具有一種 @property 裝飾器
class Goods:
def __init__(self, name):
self.name = name
@property
def price(self):
return 100
# ipython測(cè)驗(yàn)
In [10]: g = Goods('手表')
In [11]: g.price
Out[11]: 100
新式類(lèi)
新式類(lèi),具有三種 @property 裝飾器
class Goods:
"""
python3中默認(rèn)繼承object類(lèi)
以python2、3執(zhí)行此程序的結(jié)果不同,因?yàn)橹挥性趐ython3中才有@xxx.setter @xxx.deleter
"""
@property
def price(self):
print('@property')
@price.setter
def price(self, value):
print('@price.setter')
@price.deleter
def price(self):
print('@price.deleter')
# ipython測(cè)驗(yàn)
In [13]: g = Goods()
In [14]: g.price
@property
In [15]: g.price = 100
@price.setter
In [16]: del g.price
@price.deleter
g.price單獨(dú)調(diào)用自動(dòng)執(zhí)行@property修飾的price方法,并獲取方法的返回值g.price = 100賦值自動(dòng)執(zhí)行@price.setter修飾的price方法,并將100賦值給方法的參數(shù)del g.price刪除自動(dòng)執(zhí)行@price.deleter修飾的price方法
注意
- 舊式類(lèi)中的屬性只有一種訪(fǎng)問(wèn)方式,其對(duì)應(yīng)被
@property修飾的方法 - 新式類(lèi)中的屬性有三種訪(fǎng)問(wèn)方式,并分別對(duì)應(yīng)了三個(gè)被
@property、@方法名.setter、@方法名.deleter修飾的方法
由于新式類(lèi)中具有三種訪(fǎng)問(wèn)方式,我們可以根據(jù)它們幾個(gè)屬性的訪(fǎng)問(wèn)特點(diǎn),分別將三個(gè)方法定義為對(duì)同一個(gè)屬性:獲取、修改、刪除。
# Goods類(lèi)@property應(yīng)用
class Goods(object):
def __init__(self, name, price):
# 原價(jià)
self.original_price = price
# 折扣
self.discount = 0.8
@property
def price(self):
# 實(shí)際價(jià)格 = 原價(jià) * 折扣
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
print('刪除商品原價(jià)')
del self.original_price
# ipython測(cè)驗(yàn)
In [22]: g = Goods('小米手機(jī)', 2000)
In [23]: g.price
Out[23]: 1600.0
In [24]: g.price = 3000
In [25]: g.price
Out[25]: 2400.0
In [26]: del g.price
刪除商品原價(jià)
In [27]: g.price
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-38ee45b469f2> in <module>
----> 1 g.price
<ipython-input-18-d5ea66eb7ece> in price(self)
12 def price(self):
13 # 實(shí)際價(jià)格 = 原價(jià) * 折扣
---> 14 new_price = self.original_price * self.discount
15 return new_price
16
AttributeError: 'Goods' object has no attribute 'original_price'
類(lèi)屬性方式
創(chuàng)建值為 property 對(duì)象的類(lèi)屬性,當(dāng)使用類(lèi)屬性的方式創(chuàng)建 property 屬性時(shí),舊式類(lèi) 和 新式類(lèi)無(wú)區(qū)別
class Foo:
def get_bar(self):
return 'get_bar'
BAR = property(get_bar)
# ipython 測(cè)驗(yàn)
In [32]: f = Foo()
In [33]: f.BAR
Out[33]: 'get_bar'
f.BAR 自動(dòng)調(diào)用 get_bar() 方法,并獲取方法的返回值
property() 中有個(gè)四個(gè)參數(shù)
- 第一個(gè)參數(shù)是方法名,調(diào)用 對(duì)象.屬性 時(shí)自動(dòng)觸發(fā)執(zhí)行方法
- 第二個(gè)參數(shù)是方法名,調(diào)用 對(duì)象.屬性 = XXX 時(shí)自動(dòng)觸發(fā)執(zhí)行方法
- 第三個(gè)參數(shù)是方法名,調(diào)用 del 對(duì)象.屬性 時(shí)自動(dòng)觸發(fā)執(zhí)行方法
- 第四個(gè)參數(shù)是字符串,調(diào)用 對(duì)象.屬性._doc_ ,此參數(shù)是該屬性的描述信息
class Foo(object):
def __init__(self, bar):
self.bar = bar
def get_bar(self):
print('get_bar')
return self.bar
def set_bar(self, value):
"""必須要有兩個(gè)參數(shù)"""
print('set bar ' + value)
self.bar = value
def del_bar(self):
print('del bar')
del self.bar
BAR = property(get_bar, set_bar, del_bar, "bar description...")
# ipython測(cè)驗(yàn)
In [50]: f = Foo('python')
In [51]: f.BAR
get_bar
Out[51]: 'python'
In [52]: f.BAR = 'Java'
set bar Java
In [53]: f.BAR
get_bar
Out[53]: 'Java'
In [54]: del f.BAR
del bar
property對(duì)象與@property裝飾器對(duì)比
由于 類(lèi)屬性方式 創(chuàng)建 property 對(duì)象屬性具有3種訪(fǎng)問(wèn)方式,我們可以根據(jù)它們幾個(gè)屬性的訪(fǎng)問(wèn)特點(diǎn),分別將三個(gè)方法定義為對(duì) 同一個(gè)屬性:獲取、修改、刪除 ,跟 @property 裝飾器對(duì)比。
property對(duì)象類(lèi)屬性
# Goods類(lèi) property對(duì)象類(lèi)屬性 應(yīng)用
class Goods(object):
def __init__(self, name, price):
# 原價(jià)
self.original_price = price
# 折扣
self.discount = 0.8
def get_price(self):
# 實(shí)際價(jià)格 = 原價(jià) * 折扣
new_price = self.original_price * self.discount
return new_price
def set_price(self, value):
self.original_price = value
def del_price(self):
print('刪除商品原價(jià)')
del self.original_price
PRICE = property(get_price, set_price, del_price, "price description")
# ipython測(cè)驗(yàn)
In [59]: g = Goods('Mac電腦', 9000)
In [60]: g.PRICE
Out[60]: 7200.0
In [61]: g.PRICE = 10000
In [62]: g.PRICE
Out[62]: 8000.0
In [63]: del g.PRICE
刪除商品原價(jià)
@property裝飾器
# Goods類(lèi) @property裝飾器 應(yīng)用
class Goods(object):
def __init__(self, name, price):
# 原價(jià)
self.original_price = price
# 折扣
self.discount = 0.8
@property
def price(self):
# 實(shí)際價(jià)格 = 原價(jià) * 折扣
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
print('刪除商品原價(jià)')
del self.original_price
# ipython測(cè)驗(yàn)
In [59]: g = Goods('Mac電腦', 9000)
In [60]: g.PRICE
Out[60]: 7200.0
In [61]: g.PRICE = 10000
In [62]: g.PRICE
Out[62]: 8000.0
In [63]: del g.PRICE
刪除商品原價(jià)
可以發(fā)現(xiàn)兩種都可以實(shí)現(xiàn)但 @property 裝飾器的在 舊式類(lèi)中只有 @property , 沒(méi)有@method.setter 和@method.deleter,新式類(lèi)則兩種都可以使用。因此看大家的習(xí)慣,選一種。
大自然用數(shù)百億年創(chuàng)造出我們現(xiàn)實(shí)世界,而程序員用幾百年創(chuàng)造出一個(gè)完全不同的虛擬世界。我們用鍵盤(pán)敲出一磚一瓦,用大腦構(gòu)建一切。人們把1000視為權(quán)威,我們反其道行之,捍衛(wèi)1024的地位。我們不是鍵盤(pán)俠,我們只是平凡世界中不凡的締造者 。
到此這篇關(guān)于Python中關(guān)于property使用的小技巧的文章就介紹到這了,更多相關(guān)Python property 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 掌握Python property裝飾器巧妙管理類(lèi)的屬性
- python裝飾器中@property屬性的使用解析
- Python中通過(guò)property設(shè)置類(lèi)屬性的訪(fǎng)問(wèn)
- 關(guān)于python中@property的使用方法
- Python?property裝飾器使用案例介紹
- Python深入分析@property裝飾器的應(yīng)用
- python 中的@property的用法詳解
- python中@Property屬性使用方法
- Python中property屬性的用處詳解
- Python裝飾器中@property使用詳解
- Python的@property的使用
- 詳解Python裝飾器之@property
- Python property函數(shù)的具體使用
相關(guān)文章
用Python讀取幾十萬(wàn)行文本數(shù)據(jù)
今天小編就為大家分享一篇關(guān)于用Python讀取幾十萬(wàn)行文本數(shù)據(jù),小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
python人工智能tensorflow優(yōu)化器Optimizer算法匯總
這篇文章主要為大家介紹了python人工智能tensorflowtf優(yōu)化器Optimizer算法匯總,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python PyAutoGUI 模擬鼠標(biāo)鍵盤(pán)操作和截屏功能
一款跨平臺(tái)/無(wú)依賴(lài)的自動(dòng)化測(cè)試工具,目測(cè)只能控制鼠標(biāo)/鍵盤(pán)/獲取屏幕尺寸/彈出消息框/截屏。這篇文章主要介紹了python PyAutoGUI 模擬鼠標(biāo)鍵盤(pán)操作和截屏功能,需要的朋友可以參考下2019-08-08
python實(shí)現(xiàn)顏色rgb和hex相互轉(zhuǎn)換的函數(shù)
這篇文章主要介紹了python實(shí)現(xiàn)顏色rgb和hex相互轉(zhuǎn)換的函數(shù),可實(shí)現(xiàn)將rgb表示的顏色轉(zhuǎn)換成hex值的功能,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-03-03
Python調(diào)用OpenCV實(shí)現(xiàn)圖像平滑代碼實(shí)例
這篇文章主要介紹了Python調(diào)用OpenCV實(shí)現(xiàn)圖像平滑代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
pytorch 指定gpu訓(xùn)練與多gpu并行訓(xùn)練示例
今天小編就為大家分享一篇pytorch 指定gpu訓(xùn)練與多gpu并行訓(xùn)練示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
五個(gè)簡(jiǎn)單有效的Python清理數(shù)據(jù)腳本分享
通常情況下,在機(jī)器學(xué)習(xí)中的數(shù)據(jù)清理往往是一件令人頭疼的事情,本文整理了一份清單,列出了5個(gè)常用的Python腳本,用于自動(dòng)化數(shù)據(jù)清理,需要的可以參考一下2022-09-09

