一、类的扩展方法
1.静态方法
语法:@staticmethod,静态方法不能访问公有属性,不能访问类。可在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量。
1 class eat(object): 2 def __init__(self,name): 3 self.name = name 4 @staticmethod #静态方法不能访问共有属性、不能访问实例 5 def eat(name,food): 6 print("%s is eating..%s" %(name,food)) 7 p.eat("alex","food")
2.类方法
语法:@classmethod,只能访问类的公有属性,不能访问实例属性。
1 class Dog(object): 2 name = "我是类变量" 3 def __init__(self,name): 4 self.name = name 5 6 @classmethod 7 def eat(self): 8 print("%s is eating" % self.name) 9 10 11 12 d = Dog("ChenRonghua") 13 d.eat() 14 15 16 #执行结果 17 18 我是类变量 is eating
3.属性方法
语法:@property 把一个方法变成静态属性
1 class Dog(object): 2 3 def __init__(self,name): 4 self.name = name 5 6 @property 7 def eat(self): 8 print(" %s is eating" %self.name) 9 10 11 d = Dog("ChenRonghua") 12 d.eat
属性方法之航班查询代码
1 class Flight(object): 2 def __init__(self,name): 3 self.flight_name = name 4 5 6 def checking_status(self): 7 print("checking flight %s status " % self.flight_name) 8 return 1 9 10 11 @property 12 def flight_status(self): 13 status = self.checking_status() 14 if status == 0 : 15 print("flight got canceled...") 16 elif status == 1 : 17 print("flight is arrived...") 18 elif status == 2: 19 print("flight has departured already...") 20 else: 21 print("cannot confirm the flight status...,please check later") 22 23 @flight_status.setter #修改 24 def flight_status(self,status): 25 status_dic = { 26 : "canceled", 27 :"arrived", 28 : "departured" 29 } 30 print("