参考链接:http://www.cnblogs.com/alex3714/articles/5213184.html
静态方法
只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性
class Dog(object): def __init__(self,name): self.name = name @staticmethod #实际上跟类没什么关系了 def eat(self): print("%s is eating %s"%(self.name,‘dd‘)) def talk(self): print("%s is talking"%self.name) d = Dog("ChenRH") d.eat(d) d.talk()
类方法:
只能访问类变量,不能访问实例变量
class Dog(object): #n = 3333 name = "Huazai" def __init__(self,name): self.name = name #@staticmethod #实际上跟类没什么关系了 @classmethod def eat(self): print("%s is eating %s"%(self.name,‘dd‘)) def talk(self): print("%s is talking"%self.name) d = Dog("ChenRH") d.eat() d.talk()
属性方法:
把一个方法变成一个静态属性
class Dog(object): #n = 3333 name = "Huazai" def __init__(self,name): self.name = name #@staticmethod #实际上跟类没什么关系了 #@classmethod @property #attribute def eat(self): print("%s is eating %s"%(self.name,‘dd‘)) # def talk(self): # print("%s is talking"%self.name) d = Dog("ChenRH") d.eat
class Dog(object): #n = 3333 name = "Huazai" def __init__(self,name): self.name = name self.__food =None #@staticmethod #实际上跟类没什么关系了 #@classmethod @property #attribute,把一个方法变成属性 def eat(self): print("%s is eating %s"%(self.name,self.__food)) @eat.setter#修改属性 def eat(self,food): print("set to food:",food) self.__food = food @eat.deleter#删除私有属性 def eat(self): del self.__food print("删完了") # def talk(self): # print("%s is talking"%self.name) d = Dog("ChenRH") d.eat d.eat = "baozi" del d.eat
静态属性方法适用场景举例:
你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:
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
原文地址:https://www.cnblogs.com/xiaobai005/p/8358908.html
时间: 2024-10-31 03:03:30