欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

通過(guò)實(shí)例了解python property屬性

 更新時(shí)間:2019年11月01日 14:30:25   作者:張風(fēng)閑  
這篇文章主要介紹了通過(guò)實(shí)例了解python property屬性,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了通過(guò)實(shí)例了解python property屬性,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1. 什么是property屬性

一種用起來(lái)像是使用的實(shí)例屬性一樣的特殊屬性,可以對(duì)應(yīng)于某個(gè)方法

# ############### 定義 ###############
class Foo:
  def func(self):
    pass

  # 定義property屬性
  @property
  def prop(self):
    pass

# ############### 調(diào)用 ###############
foo_obj = Foo()
foo_obj.func() # 調(diào)用實(shí)例方法
foo_obj.prop # 調(diào)用property屬性

如下的例子用于說(shuō)明如何定一個(gè)簡(jiǎn)單的property屬性:

class Goods(object):
    @property
    def size(self):
        return 100 
g = Goods()
print(g.size)

property屬性的定義和調(diào)用要注意一下幾點(diǎn):

  • 定義時(shí),在實(shí)例方法的基礎(chǔ)上添加 @property 裝飾器;并且僅有一個(gè)self參數(shù)
  • 調(diào)用時(shí),無(wú)需括號(hào)

2. 簡(jiǎn)單的實(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ù)用戶請(qǐng)求的當(dāng)前頁(yè)和總數(shù)據(jù)條數(shù)計(jì)算出 m 和 n
  • 根據(jù)m 和 n 去數(shù)據(jù)庫(kù)中請(qǐng)求數(shù)據(jù)
# ############### 定義 ###############
class Pager:
  def __init__(self, current_page):
    # 用戶當(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

# ############### 調(diào)用 ###############
p = Pager(1)
p.start # 就是起始值,即:m
p.end # 就是結(jié)束值,即:n

從上述可見(jiàn):

Python的property屬性的功能是:property屬性內(nèi)部進(jìn)行一系列的邏輯計(jì)算,最終將計(jì)算結(jié)果返回。

3. property屬性的有兩種方式

  • 裝飾器 即:在方法上應(yīng)用裝飾器
  • 類屬性 即:在類中定義值為property對(duì)象的類屬性

3.1 裝飾器方式

在類的實(shí)例方法上應(yīng)用@property裝飾器

Python中的類有經(jīng)典類和新式類,新式類的屬性比經(jīng)典類的屬性豐富。( 如果類繼object,那么該類是新式類 )

經(jīng)典類,具有一種@property裝飾器:

# ############### 定義 ###############  
class Goods:
  @property
  def price(self):
    return "laowang"
# ############### 調(diào)用 ###############
obj = Goods()
result = obj.price # 自動(dòng)執(zhí)行 @property 修飾的 price 方法,并獲取方法的返回值
print(result)

新式類,具有三種@property裝飾器:

#coding=utf-8
# ############### 定義 ###############
class Goods:
  """python3中默認(rèn)繼承object類
    以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')

# ############### 調(diào)用 ###############
obj = Goods()
obj.price     # 自動(dòng)執(zhí)行 @property 修飾的 price 方法,并獲取方法的返回值
obj.price = 123  # 自動(dòng)執(zhí)行 @price.setter 修飾的 price 方法,并將 123 賦值給方法的參數(shù)
del obj.price   # 自動(dòng)執(zhí)行 @price.deleter 修飾的 price 方法

注意:

  • 經(jīng)典類中的屬性只有一種訪問(wèn)方式,其對(duì)應(yīng)被 @property 修飾的方法
  • 新式類中的屬性有三種訪問(wèn)方式,并分別對(duì)應(yīng)了三個(gè)被@property、@方法名.setter、@方法名.deleter修飾的方法

由于新式類中具有三種訪問(wèn)方式,我們可以根據(jù)它們幾個(gè)屬性的訪問(wèn)特點(diǎn),分別將三個(gè)方法定義為對(duì)同一個(gè)屬性:獲取、修改、刪除

class Goods(object):

  def __init__(self):
    # 原價(jià)
    self.original_price = 100
    # 折扣
    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):
    del self.original_price

obj = Goods()
obj.price     # 獲取商品價(jià)格
obj.price = 200  # 修改商品原價(jià)
del obj.price   # 刪除商品原價(jià)

3.2 類屬性方式,創(chuàng)建值為property對(duì)象的類屬性

當(dāng)使用類屬性的方式創(chuàng)建property屬性時(shí),經(jīng)典類和新式類無(wú)區(qū)別

class Foo:
  def get_bar(self):
    return 'laowang'

  BAR = property(get_bar)

obj = Foo()
reuslt = obj.BAR # 自動(dòng)調(diào)用get_bar方法,并獲取方法的返回值
print(reuslt)

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ù)是該屬性的描述信息
#coding=utf-8
class Foo(object):
  def get_bar(self):
    print("getter...")
    return 'laowang'

  def set_bar(self, value): 
    """必須兩個(gè)參數(shù)"""
    print("setter...")
    return 'set value' + value

  def del_bar(self):
    print("deleter...")
    return 'laowang'

  BAR = property(get_bar, set_bar, del_bar, "description...")

obj = Foo()

obj.BAR # 自動(dòng)調(diào)用第一個(gè)參數(shù)中定義的方法:get_bar
obj.BAR = "alex" # 自動(dòng)調(diào)用第二個(gè)參數(shù)中定義的方法:set_bar方法,并將“alex”當(dāng)作參數(shù)傳入
desc = Foo.BAR.__doc__ # 自動(dòng)獲取第四個(gè)參數(shù)中設(shè)置的值:description...
print(desc)
del obj.BAR # 自動(dòng)調(diào)用第三個(gè)參數(shù)中定義的方法:del_bar方法

由于類屬性方式創(chuàng)建property屬性具有3種訪問(wèn)方式,我們可以根據(jù)它們幾個(gè)屬性的訪問(wèn)特點(diǎn),分別將三個(gè)方法定義為對(duì)同一個(gè)屬性:獲取、修改、刪除

class Goods(object):

  def __init__(self):
    # 原價(jià)
    self.original_price = 100
    # 折扣
    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):
    del self.original_price

  PRICE = property(get_price, set_price, del_price, '價(jià)格屬性描述...')

obj = Goods()
obj.PRICE     # 獲取商品價(jià)格
obj.PRICE = 200  # 修改商品原價(jià)
del obj.PRICE   # 刪除商品原價(jià)

綜上所述:

  • 定義property屬性共有兩種方式,分別是【裝飾器】和【類屬性】,而【裝飾器】方式針對(duì)經(jīng)典類和新式類又有所不同。
  • 通過(guò)使用property屬性,能夠簡(jiǎn)化調(diào)用者在獲取數(shù)據(jù)的流程

4. property屬性-應(yīng)用

4.1. 私有屬性添加getter和setter方法

class Money(object):
  def __init__(self):
    self.__money = 0

  def getMoney(self):
    return self.__money

  def setMoney(self, value):
    if isinstance(value, int):
      self.__money = value
    else:
      print("error:不是整型數(shù)字")

4.2. 使用property升級(jí)getter和setter方法

class Money(object):
  def __init__(self):
    self.__money = 0

  def getMoney(self):
    return self.__money

  def setMoney(self, value):
    if isinstance(value, int):
      self.__money = value
    else:
      print("error:不是整型數(shù)字")

  # 定義一個(gè)屬性,當(dāng)對(duì)這個(gè)money設(shè)置值時(shí)調(diào)用setMoney,當(dāng)獲取值時(shí)調(diào)用getMoney
  money = property(getMoney, setMoney) 

a = Money()
a.money = 100 # 調(diào)用setMoney方法
print(a.money) # 調(diào)用getMoney方法
#100

4.3. 使用property取代getter和setter方法

重新實(shí)現(xiàn)一個(gè)屬性的設(shè)置和讀取方法,可做邊界判定

class Money(object):
  def __init__(self):
    self.__money = 0

  # 使用裝飾器對(duì)money進(jìn)行裝飾,那么會(huì)自動(dòng)添加一個(gè)叫money的屬性,當(dāng)調(diào)用獲取money的值時(shí),調(diào)用裝飾的方法
  @property
  def money(self):
    return self.__money

  # 使用裝飾器對(duì)money進(jìn)行裝飾,當(dāng)對(duì)money設(shè)置值時(shí),調(diào)用裝飾的方法
  @money.setter
  def money(self, value):
    if isinstance(value, int):
      self.__money = value
    else:
      print("error:不是整型數(shù)字")

a = Money()
a.money = 100
print(a.money)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 基于Python制作GIF表情包生成工具

    基于Python制作GIF表情包生成工具

    在當(dāng)前無(wú)表情包不會(huì)聊天的時(shí)代,怎么也不能輸在表情包數(shù)量不足上啊,今天咱們就來(lái)基于Python制作一個(gè)?gif?生成工具,用來(lái)制作表情包也太好用啦
    2023-07-07
  • 詳解python調(diào)度框架APScheduler使用

    詳解python調(diào)度框架APScheduler使用

    本篇文章主要介紹了詳解python調(diào)度框架APScheduler使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-03-03
  • 詳解Python字典小結(jié)

    詳解Python字典小結(jié)

    這篇文章主要介紹了詳解Python字典小結(jié),詳細(xì)的介紹了什么是字典且創(chuàng)建字典和示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2018-10-10
  • Python實(shí)現(xiàn)的簡(jiǎn)單dns查詢功能示例

    Python實(shí)現(xiàn)的簡(jiǎn)單dns查詢功能示例

    這篇文章主要介紹了Python實(shí)現(xiàn)的簡(jiǎn)單dns查詢功能,結(jié)合實(shí)例形式分析了Python基于socket模塊的dns信息查詢實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2017-05-05
  • python smtplib模塊實(shí)現(xiàn)發(fā)送郵件帶附件sendmail

    python smtplib模塊實(shí)現(xiàn)發(fā)送郵件帶附件sendmail

    這篇文章主要為大家詳細(xì)介紹了python smtplib模塊實(shí)現(xiàn)發(fā)送郵件帶附件sendmail,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • python 查找字符串是否存在實(shí)例詳解

    python 查找字符串是否存在實(shí)例詳解

    這篇文章主要介紹了python 查找字符串是否存在實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-01-01
  • python中的斷言(assert語(yǔ)句)

    python中的斷言(assert語(yǔ)句)

    這篇文章主要介紹了python中的斷言(assert語(yǔ)句),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Python實(shí)現(xiàn)重建二叉樹(shù)的三種方法詳解

    Python實(shí)現(xiàn)重建二叉樹(shù)的三種方法詳解

    這篇文章主要介紹了Python實(shí)現(xiàn)重建二叉樹(shù)的三種方法,結(jié)合實(shí)例形式分析了Python重建二叉樹(shù)的實(shí)現(xiàn)方法、操作技巧與注意事項(xiàng),需要的朋友可以參考下
    2018-06-06
  • Python字典操作得力助手Get()函數(shù)的使用

    Python字典操作得力助手Get()函數(shù)的使用

    在Python編程中,get()函數(shù)是字典(Dictionary)對(duì)象中非常有用的函數(shù),本文將詳細(xì)介紹get()函數(shù)的用法及示例代碼,感興趣的可以了解一下
    2023-11-11
  • 淺析Python迭代器的高級(jí)用法

    淺析Python迭代器的高級(jí)用法

    這篇文章主要介紹了Python迭代器的高級(jí)用法,在實(shí)際場(chǎng)景當(dāng)中非常實(shí)用,可以幫助我們大大簡(jiǎn)化代碼的復(fù)雜度。感興趣的朋友可以了解下
    2020-07-07

最新評(píng)論