@staticmethod
静态方法:相当于一个单独的函数,只是名义上归类管,实际上在静态方法里访问不了类或实例中的任何属性,也即跟类没什么关系了。
代码范例:
#!/usr/bin/env python # -*- coding: utf-8 -*- class C1(object): name = 'ff' def __init__(self,name): self.name = name @classmethod # 类方法关键字 def eat(self): print('%s is eating %s' % (self.name,'food')) p = C1('hh') p.eat() # 调用类方法 #输出: hh is eating food
@classmethod
类方法:只能访问类变量(公有属性),不能访问实例变量。
代码范例:
#!/usr/bin/env python # -*- coding: utf-8 -*- class C1(object): name = 'ff' def __init__(self,name): self.name = name @classmethod # 类方法关键字 def eat(self): print('%s is eating %s' % (self.name,'food')) p = C1('hh') p.eat() # 调用类方法 #输出: hh is eating food
@property
属性方法:把一个方法变成一个静态属性。(隐藏实现细节)
代码范例1:
#!/usr/bin/env python # -*- coding: utf-8 -*- class C1(object): def __init__(self,name): self.name = name self.__food = None @property # 类属性关键字 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): print('delete succeed!') p = C1('hh') p.eat # 类属性调用 p.eat = 'dd' # 类属性设置 p.eat # del p.name # print(p.name) del p.eat # 类属性删除 #输出: hh is eating None set to food: dd hh is eating dd delete succeed!
范例2:
#!/usr/bin/env python # -*- coding: utf-8 -*- class Flight(object): def __init__(self,name): self.flight_name = name def checking_status(self): print("checking flight %s status " % self.flight_name) return 0 @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): print("flight status is change to",status) f = Flight("CA980") f.flight_status f.flight_status = 2 #输出 checking flight CA980 status flight got canceled... flight status is change to 2
posted on
浙公网安备 33010602011771号