静态方法@staticmethod:不可访问类中的变量与方法,唯一的关联就是通过类名去调用
class Dog(object): def __init__(self,name): self.name = name @staticmethod def eat(name): print("%s is eating" % name) d = Dog("alex") d.eat("hehe")
类方法@classmethod:只能访问类变量,不能访问实例变量
class Dog(object): name = "我是类变量" def __init__(self,name): self.name = name @classmethod def eat(self): print("%s is eating" % self.name) d = Dog("alex") d.eat()
属性方法@property:把类里面的方法变成属性,其跟普通类没有关系
class Dog(object): name = "我是类变量" def __init__(self,name): self.name = name @property def eat(self): print("%s is eating" % self.name) d = Dog("alex") d.eat
属性方法例子
1 class Flight(object): 2 def __init__(self,name): 3 self.flight = name 4 self.status = 1 5 6 def checking_status(self): 7 print("checking flight %s status %s" % (self.flight,self.status)) 8 9 @property 10 def flight_status(self): 11 if self.status == 0: 12 print("flight got canceled...") 13 elif self.status == 1: 14 print("flight is arrived...") 15 elif self.status == 2: 16 print("flight has departured already...") 17 else: 18 print("cannot confirm the flight status...,please check later") 19 20 @flight_status.setter # 修改属性,不添加修改属性无法直接修改 21 def flight_status(self,status): 22 self.status = status 23 print("flight status change %s" % self.status) 24 25 @flight_status.deleter # 删除属性 26 def flight_status(self): 27 del self.status 28 print("status got remove....") 29 30 f = Flight("CA980") 31 32 f.flight_status 33 34 f.flight_status = 2 35 36 f.checking_status() 37 38 f.flight_status 39 40 del f.flight_status 41 42 # f.flight_status
类中特殊成员方法
__doc__ : 类的描述信息
__module__ : 当前操作的对象在哪个模块
__class__ : 当前操作的对象的类名
__init__ : 构造方法,通过类创建对象时自动触发执行
__del__ : 析构方法,当对象在内存中被释放时自动触发执行(解释器进行垃圾回收时自动执行)
__call__ : 对象后加(),触发执行(由对象后加括号触发的,即:对象() 或者 类()())
1 class Foo(object): 2 def __init__(self): 3 pass 4 5 def __call__(self, *args, **kwargs): 6 print("__call__") 7 8 def talk(self): 9 print("talk") 10 obj = Foo() 11 print(obj) 12 obj() 13 obj.talk()
__dict__ : 查看类或对象中的所有成员
1 class Province(object): 2 country = "China" 3 def __init__(self,name,count): 4 self.name = name 5 self.count = count 6 7 def func(self,*args,**kwargs): 8 print('func') 9 10 print("