日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python中property方法有用_python中@property和property函数常见使用方法示例

發(fā)布時(shí)間:2024/9/15 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中property方法有用_python中@property和property函数常见使用方法示例 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文實(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()

運(yùn)行結(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

運(yùn)行結(jié)果:

@price.setter:50

@property

@price.deleter

3、@property demo

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

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):

'''必須兩個(gè)參數(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)用第四個(gè)描述

print(desc)

del obj.NAME #調(diào)用第三個(gè)刪除方法

運(yùn)行結(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))

運(yùn)行結(jié)果:

20

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:

總結(jié)

以上是生活随笔為你收集整理的python中property方法有用_python中@property和property函数常见使用方法示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。