Python有三種裝飾器,分別是靜態方法、類方法、靜態屬性。前兩種個人覺得沒啥用,只是概念上知道一下有這個用法,最後一個還是可以用下的。
1.靜態方法:@staticmethod裝飾器 @staticmethod 與類無關 def fun():
2.類方法: @classmethod @classmethod 訪問類變量,不能訪問實例變量 def fun(self):
3.靜態屬性:@property 屬性賦值 隱藏實現細節
上代碼:
class myclass(object):
n=333
def __init__(self, name):
self.name = name
@staticmethod # 1.把fun1方法變爲靜態方法 不可以有self 與類沒有關係
def fun1(): # 如果寫成 def fun1(self) 是會報錯的
print("fun1" )
@classmethod # 2.只能訪問類變量,不能訪問實例變量
def fun2(self):
print("fun2%s " % (self.n))
@property #3.屬性 只寫結果
def fun3(self):
print(" %s is fun3%s" % (self.name,'ddd'))
@fun3.setter #修改變量在這
def fun3(self,food):
print("set to fun3:",food)
self._food=food
@fun3.deleter
def fun3(self,food):
del self._food
d = myclass("mytestclass")
d.fun3
d.fun3="baozi"
以下是從網上其它處轉載的一個@property使用實例:
比如 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、還是已經飛走了, 想知道這種狀態你必須經歷以下幾步:
1. 連接航空公司API查詢
2. 對查詢結果進行解析
3. 返回結果給你的用戶
因此這個status屬性的值是一系列動作後纔得到的結果,所以你每次調用時,其實它都要經過一系列的動作才返回你結果,但這些動作過程不需要用戶關心, 用戶只需要調用這個屬性就可以,
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 1
@property
def flight_status(self):
status = self.checking_status()
if status == 0 :
print("flight got canceled...")
elif status == 1 :
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
@flight_status.setter #修改
def flight_status(self,status):
status_dic = {
0 : "canceled",
1 :"arrived",
2 : "departured"
}
print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) )
@flight_status.deleter #刪除
def flight_status(self):
print("status got removed...")
f = Flight("CA980")
f.flight_status
f.flight_status = 2 #觸發@flight_status.setter
del f.flight_status #觸發@flight_status.deleter