class 類名:
@property
def 方法名(silf):
return 返回值
物件 = 類()
變數 = 物件.方法名
print(變數)
注:
建立流程:
class goods():
@property
def price(self):
print("@proterty")
@price.setter
def price(self,value):
print("@proterty.setter")
@price.deleter
def price(self):
print("@proterty.deleter")
g = goods()
g.price # 獲取
g.price = value # 設定
del g.price # 刪除
注:
應用01:
class goods:
def __init__(self):
# 原價
self.original_prince = 100
# 折扣
self.discount = 0.8
@property
def price(self):
# 實際** = 原價 + 折扣
new_price = self.original_prince *self.discount
return new_price
@price.setter
def price(self,value):
self.original_prince = value
@price.deleter
def price(self):
del self.original_prince
obj = goods()
print(obj.price) # 獲取商品**
obj.price = 200 # 修改商品原價
print(obj.price)
del obj.price # 刪除商品原價
# print(obj.prince)
建立流程:
class foo:
def get_bar(self):
return "zhangsan"
bar = property(get_bar)
f = foo()
reuslt = f.bar # 自動呼叫get_bar方法,並獲取方法的返回值
print(reuslt)
注:
應用01:
#coding=utf-8class foo(object):
def get_bar(self):
print("getter...")
return 'laowang'
def set_bar(self, value):
"""必須兩個引數"""
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 # 自動呼叫第乙個引數中定義的方法:get_bar
obj.bar = "alex" # 自動呼叫第二個引數中定義的方法:set_bar方法,並將「alex」當作引數傳入
desc = foo.bar.__doc__ # 自動獲取第四個引數中設定的值:description...
print(desc)
del obj.bar # 自動呼叫第三個引數中定義的方法:del_bar方法
應用02: 使用property公升級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:不是整型數字")
# 定義乙個屬性,當對這個money設定值時呼叫setmoney,當獲取值時呼叫getmoney
money = property(getmoney, setmoney)
a = money()
a.money = 100 # 呼叫setmoney方法
print(a.money) # 呼叫getmoney方法
#100
Python的 property的使用
目錄 通rujnlcdyh常,當我們需要對物件的敏感屬性或者不希望外部直接訪問的屬性進行私有化,但是某些時候我們又需要對這些私有屬性進行修改,該怎麼處理呢?定義乙個類 class student object male age 0 執行 私有屬性無法在外部訪問 stu student stu.mal...
python中的 property使用
如下 class animal object def init self,name,age self.name name self.age age a animal zhuzhu 9 a.name out 3 zhuzhu a.age out 4 9 a.age 20 a.age out 5 20在...
python 中 property的使用
從14年下半年開始接觸到python,自學了一段時間,後又跟別人學習了下,把基礎知識基本上學過了。忽然感覺python不可能這麼簡單吧,就這麼點東西?後來看了下書,發現還有很多的高階部分。連續看了兩天,把裝飾符 看了下,記錄下。裝飾符的作用就是類裡的方法變成屬性使用,比直接呼叫方法要直接簡單 直接上...