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