C语言基础学习PYTHON——基础学习D07
20180826内容纲要:
面向对象进阶学习
1 静态方法
2 类方法
3 属性方法
4 类的特殊成员方法(本节重点)
5 反射(本节重点)
6 异常(本节重点)
7 动态导入模块
8 小结
9 练习
0 类的创建(补充)
1 class Foo(object): 2 def __init__(self,name): 3 self.name = name 4 5 f =Foo("erha") 6 print(type(f)) 7 print(type(Foo)) 8 #输出结果: 9 # <class '__main__.Foo'> 10 # <class 'type'> 11 #发现f的类型是 类__main__.Foo,而Foo的类型是 类,类型
1 #那么我们来看一下类的第二种创建方法 2 def func(self): 3 print("ni shi sha zi ba") 4 5 Foo =type('Foo',(),{'func':func}) 6 f =Foo() 7 f.func() 8 print(type(Foo)) 9 ''' 10 #这样看上和第一种有点不一样,因为没有构造函数还没有传参。那怎么操作呢? 11 12 def func(self): 13 print("%s 今年 %s 岁了"%(self.name,self.age)) 14 15 def __init__(self,name,age): 16 self.name = name 17 self.age = age 18 19 Foo =type('Foo',(object,),{'func':func, 20 '__init__':__init__}) 21 f =Foo('kanghui',22) 22 f.func()
类是由type类实例化产生的。
那么类的创建过程是怎样的呢?类中有一个属性 __metaclass__,其用来表示该类由谁来实例化创建
所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看类创建的过程。
metaclass 详解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
1 #Author:ZhangKanghui 2 3 class MyType(type): 4 def __init__(self,what,bases=None,dict=None): 5 print("MyType--------init") 6 super(MyType,self).__init__(what,bases,dict) 7 def __call__(self, *args, **kwargs): 8 print("MyType-------call") 9 obj = self.__new__(self,*args,**kwargs) 10 self.__init__(self,*args,**kwargs) 11 12 13 class Foo(object): 14 __metaclass__ = MyType 15 16 def __init__(self,name): 17 self.name = name 18 print("Foo-----init") 19 def __new__(cls, *args, **kwargs): 20 print("Foo----new") 21 print(object.__new__(cls)) #通过执行结果们可以看出return的返回值就是Foo的内存地址 22 return object.__new__(cls) #继承父类的new方法 23 24 25 #看不懂没关系,我们先来实例化一下看看都在干吗 26 obj =Foo("erha") 27 #执行结果:先执行new再执行init,这是为什么呢? 28 # Foo----new 29 # Foo-----init 30 31 #这个时候我们把new中的return注释掉看一下执行结果。 32 #Foo----new 只执行了new,根本没有实例化。不信可以试一下 print(obj.name) 33 #所以new使用来创建实例的 34 #取消return的注释再执行一下 35 print(obj.name)
1 静态方法 @staticmethod
与类无关,不能访问类里的任何变量
只是名义上归类管理,但实际上静态方法里访问不了类和实例中的任何属性。只是名义上归类管理,但实际上静态方法里访问不了类和实例中的任何属性。
1 #Author:ZhangKanghui 2 #先来大概认识一下staticmethod 3 4 class Dog(object): 5 def __init__(self,name): 6 self.name = name 7 @staticmethod #这就跟类没有什么关系了,下面的这个只是一个貌似属于类的函数 8 def eat(self,food): 9 print("%s is eating %s" %(self.name,food)) 10 11 d =Dog("二哈") 12 d.eat("baozi") 13 14 #正常情况下是可以运行的,但是在eat函数上加一个@staticmethod在运行一下看看 15 #TypeError: eat() missing 1 required positional argument: 'food' 16 #这就跟类没有什么关系了,下面的这个只是一个貌似属于类的函数
@staticmethod
通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法
上面的调用会出错误,说是eat需要一个self参数,但调用时却没有传递。
没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。
想让上面的代码可以正常工作有两种办法
1. 调用时主动传递实例本身给eat方法,即d.eat(d)
2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了。这就是静态方法。
1 class Dog(object): 2 def __init__(self,name): 3 self.name = name 4 5 @staticmethod 6 def eat(): 7 print(" is eating") 8 d = Dog("二哈") 9 d.eat()
@staticmethod
2 类方法 @classmethod
只能访问类变量不能访问实例变量。
如果存在类变量和实例变量相同时,正常情况下会先访问实例变量,然后访问类变量。如果使用类方法则可以强制去访问类变量。
1 #Author:ZhangKanghui 2 3 class Dog(object): 4 n = "哈士奇" 5 def __init__(self,name): 6 self.name = name 7 @classmethod #这就跟类没有什么关系了,下面的这个只是一个貌似属于类的函数 8 def eat(self,food): 9 #print("%s is eating %s" %(self.name,food)) 10 print("%s is eating %s" %(self.n,food)) 11 12 d =Dog("二哈") 13 d.eat("baozi") 14 #这样直接运行会报错 AttributeError: type object 'Dog' has no attribute 'name' 15 #此时我们在类下面加一个类变量,然后用self.n调用它
类方法通过@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 d = Dog("二哈") 11 d.eat() 12 13 14 #执行结果 15 16 我是类变量 is eating
3 属性方法 @property
属性方法的作用就是通过@property把一个方法变成一个静态属性
1 #Author:ZhangKanghui 2 ''' 3 class Dog(object): 4 def __init__(self,name): 5 self.name = name 6 7 @property 8 def eat(self): 9 print("%s is eating %s" %(self.name,"baozi")) 10 11 # d =Dog("二哈") 12 # d.eat 13 #这样就是属性方法,根据运行结果可以发现能够正常运行但是不能传参了 14 #那么如果想要传参怎么办呢? 15 16 @eat.setter 17 def eat(self,food): 18 print("set to food:",food) 19 20 d =Dog("二哈") 21 d.eat 22 d.eat ="roubaozi" 23 #此时发现虽然给d.eat这个静态方法赋值但是并没有将参数传进去。那怎么做呢? 24 ''' 25 class Dog(object): 26 def __init__(self,name): 27 self.name = name 28 self.__food = None 29 @property 30 def eat(self): 31 print("%s is eating %s" %(self.name,self.__food)) 32 33 @eat.setter 34 def eat(self,food): 35 #print("set to food:", food) 36 self.__food = food 37 38 @eat.deleter 39 def eat(self): 40 del self.__food 41 print("删除了吗") 42 43 d =Dog("二哈") 44 d.eat 45 d.eat ="roubaozi" 46 d.eat 47 48 #那么属性可以删除吗? 49 #del d.eat 你会发现报错了 删不掉 50 #如果是真的想删除呢? 再加一个@eat.deleter 51 del d.eat
综上,写一段代码:航班查询
1. 连接航空公司API查询
2. 对查询结果进行解析
3. 返回结果给你的用户
1 #Author:ZhangKanghui 2 3 class Flight(object): 4 def __init__(self,name): 5 self.flight_name = name 6 def checking_status(self): 7 print("checking flight %s status " % self.flight_name) 8 return 1 9 def flight_status(self): 10 status = self.checking_status() 11 if status == 0 : 12 print("flight got canceled...") 13 elif status == 1 : 14 print("flight is arrived...") 15 elif status == 2: 16 print("flight has departured already...") 17 else: 18 print("cannot confirm the flight status...,please check later") 19 20 f = Flight("CA980") 21 f.flight_status()
变成属性之后能否赋值呢?当然可以改, 不过需要通过@proerty.setter装饰器再装饰一下。
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 0 : "canceled", 27 1 :"arrived", 28 2 : "departured" 29 } 30 print("