python中@property和property函數(shù)常見使用方法示例
本文實例講述了python中@property和property函數(shù)常見使用方法。分享給大家供大家參考,具體如下:
1、基本的@property使用,可以把函數(shù)當(dāng)做屬性用
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(shè)計入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
使用Python代碼實現(xiàn)Linux中的ls遍歷目錄命令的實例代碼
這次我就要試著用 Python 來實現(xiàn)一下 Linux 中的 ls 命令, 小小地證明下 Python 的不簡單,需要的朋友可以參考下2019-09-09
學(xué)習(xí)python如何處理需要登錄的網(wǎng)站步驟
這篇文章主要為大家介紹了python如何處理需要登錄的網(wǎng)站步驟學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
Python字典推導(dǎo)式將cookie字符串轉(zhuǎn)化為字典解析
這篇文章主要介紹了Python字典推導(dǎo)式將cookie字符串轉(zhuǎn)化為字典解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
Python自動化操作Excel方法詳解(xlrd,xlwt)
Excel是Windows環(huán)境下流行的、強大的電子表格應(yīng)用。本文將詳解用Python利用xlrd和xlwt實現(xiàn)自動化操作Excel的方法詳細(xì),需要的可以參考一下2022-06-06

