python中@property和property函數(shù)常見使用方法示例
本文實例講述了python中@property和property函數(shù)常見使用方法。分享給大家供大家參考,具體如下:
1、基本的@property使用,可以把函數(shù)當做屬性用
class Person(object): @property def get_name(self): print('我叫xxx') def main(): person = Person() person.get_name if __name__ == '__main__': main()
運行結(jié)果:
我叫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 = 50 obj.price del obj.price
運行結(jié)果:
@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_price obj = Goods() obj.price obj.price = 200 del obj.price
4、property函數(shù)使用
class Foo(object): def get_name(self): print('get_name') return 'laowang' def set_name(self, value): '''必須兩個參數(shù)''' 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 #調(diào)用get方法 obj.NAME = 'alex' #調(diào)用set方法 desc = Foo.NAME.__doc__ #調(diào)用第四個描述 print(desc) del obj.NAME #調(diào)用第三個刪除方法
運行結(jié)果:
get_name
set_name
description.
del_name
5、property函數(shù)操作私有屬性的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 = 20 print(str(person.AGE))
運行結(jié)果:
20
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關(guān)文章
Python利用atexit模塊實現(xiàn)優(yōu)雅處理程序退出
Python的atexit模塊提供了一種方便的方式來注冊這些退出時執(zhí)行的函數(shù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-03-03python networkx 根據(jù)圖的權(quán)重畫圖實現(xiàn)
這篇文章主要介紹了python networkx 根據(jù)圖的權(quán)重畫圖實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Numpy 數(shù)組操作之元素添加、刪除和修改的實現(xiàn)
本文主要介紹了Numpy 數(shù)組操作之元素添加、刪除和修改的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-03-03