国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中@property和property函數常見使用方法示例

2019-11-02 14:08:14
字體:
來源:轉載
供稿:網友

本文實例講述了python中@property和property函數常見使用方法。分享給大家供大家參考,具體如下:

1、基本的@property使用,可以把函數當做屬性用

class Person(object):  @property  def get_name(self):    print('我叫xxx')def main():  person = Person()  person.get_nameif __name__ == '__main__':  main()

運行結果:

我叫xxx

2、@property的set,deleter,get

class Goods(object):  @property  def price(self):    print('@property')  @price.setter  def price(self,value):    print('@price.setter:'+str(value))  @price.deleter  def price(self):    print('@price.deleter')obj = Goods()obj.price = 50obj.pricedel obj.price

運行結果:

@price.setter:50
@property
@price.deleter

3、@property demo

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.deleter  def price(self):    del self.original_priceobj = Goods()obj.priceobj.price = 200del obj.price

4、property函數使用

class Foo(object):  def get_name(self):    print('get_name')    return 'laowang'  def set_name(self, value):    '''必須兩個參數'''    print('set_name')    return 'set value' + value  def del_name(self):    print('del_name')    return 'laowang'  NAME = property(get_name, set_name, del_name, 'description.')obj = Foo()obj.NAME  #調用get方法obj.NAME = 'alex'  #調用set方法desc = Foo.NAME.__doc__   #調用第四個描述print(desc)del obj.NAME  #調用第三個刪除方法

運行結果:

get_name
set_name
description.
del_name

5、property函數操作私有屬性的get和set方法

class Person(object):  def __init__(self, age):    self.__age = age  def set_age(self, value):    self.__age = value  def get_age(self):    return self.__age  AGE = property(get_age, set_age)person = Person(15)person.AGE = 20print(str(person.AGE))

運行結果:

20

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 明光市| 城市| 普兰县| 磐石市| 日土县| 霞浦县| 大足县| 衡水市| 九龙城区| 德保县| 宜兰市| 唐海县| 蒙山县| 张掖市| 桓仁| 荣昌县| 永定县| 安岳县| 宣恩县| 缙云县| 洛隆县| 邵阳县| 舒兰市| 驻马店市| 黔西县| 侯马市| 平远县| 剑阁县| 井研县| 康乐县| 江北区| 龙陵县| 弥勒县| 遂平县| 新昌县| 都昌县| 随州市| 钦州市| 贡山| 化德县| 穆棱市|