zoukankan      html  css  js  c++  java
  • day07

    本节内容:

    • 面向对象高级语法部分异常处理异常处理异常处理
      • 经典类vs新式类  
      • 静态方法、类方法、属性方法
      • 类的特殊方法
      • 反射
    • 异常处理
    • 作业:开发一个支持多用户在线的FTP程序

     

    面向对象高级语法部分

    1、经典类vs新式类

    参考:http://www.cnblogs.com/ant-colonies/p/6719724.html

     

    2、实例方法、静态方法、类方法、属性方法

    2.1 实例方法

     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5     def __init__(self, name):
     6         self.name = name
     7         print('name = %s' %self.name)
     8     def sleep(self):
     9         print('going to sleep...')
    10 
    11 print(Dog.sleep)
    12 '''<unbound method Dog.sleep>'''
    13 
    14 Dog.sleep()
    15 '''
    16 Traceback (most recent call last):
    17   File "py_instance.py", line 12, in <module>
    18     Dog.sleep()
    19 TypeError: unbound method sleep() must be called with Dog instance as first argument (got nothing instead)
    20 '''
    21 '''
    22 Dog.sleep是未绑定的方法
    23 必须以类Dog的实例对象作为未绑定的方法sleep()的第一参数,sleep方法才能被调用
    24 '''
    未实例化类调用实例方法
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5     def __init__(self, name):
     6         self.name = name
     7         print('self.name = %s' %self.name)
     8         print('self : %s' %type(self))
     9     def sleep():
    10         print('going to sleep...')
    11 
    12 d = Dog('Tim')
    13 print(d.sleep)
    14 d.sleep()
    15 
    16 '''
    17 一旦实例化, __init__方法立即执行
    18 self.name = Tim
    19 
    20 self是一个类对象
    21 self : <class '__main__.Dog'>     
    22 
    23 通过实例化,使得Dog.sleep实现绑定
    24 <bound method Dog.sleep of <__main__.Dog object at 0x7ffa7deeedd0>>
    25 
    26 d.sleep()将实例对象作为第一参数传给sleep方法,但是sleep方法无形参
    27 Traceback (most recent call last):
    28   File "py_instance.py", line 14, in <module>
    29     d.sleep()
    30 TypeError: sleep() takes no arguments (1 given)
    31 '''
    实例方法无形参
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5     def __init__(self, name):
     6         self.name = name
     7         print('self.name = %s' %self.name)
     8         print('self : %s' %type(self))
     9     def sleep(name):
    10         print('%s going to sleep...' %name)
    11         print('%s going to sleep...' %name.name)
    12 
    13 d = Dog('Tim')
    14 print(d.sleep)
    15 d.sleep()
    16 
    17 '''
    18 self.name = Tim
    19 self : <class '__main__.Dog'>
    20 
    21 实例对象的内存地址
    22 <bound method Dog.sleep of <__main__.Dog object at 0x7fb3f2605dd0>>
    23 
    24 诶,实例对象传给了name
    25 <__main__.Dog object at 0x7f98f2176ed0> going to sleep...
    26 Tim going to sleep...
    27 '''
    实例方法中第一参数为实例对象
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5     def __init__(self, name):
     6         self.name = name
     7         print('self.name = %s' %self.name)
     8         print('self : %s' %type(self))
     9     def sleep(self):
    10         print('%s going to sleep...' %self.name)
    11 
    12 d = Dog('Tim')
    13 print(d.sleep)
    14 d.sleep()
    15 
    16 '''
    17 self.name = Tim
    18 self : <class '__main__.Dog'>
    19 <bound method Dog.sleep of <__main__.Dog object at 0x7f627e678e90>>
    20 
    21 python中实例方法中的第一参数为实例对象本身, 默认self作为第一形参
    22 Tim going to sleep...
    23 '''
    Python中实例方法中形参的默认表示方式
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5     def __init__(self, name):
     6         self.name = name
     7         print('self.name = %s' %self.name)
     8         print('self : %s' %type(self))
     9     def sleep(self):
    10         print('%s going to sleep...' %self.name)
    11 
    12 d = Dog('Tim')
    13 f = Dog('Tim')
    14 print(d == f)
    15 print(d.sleep is f.sleep())
    16 
    17 '''
    18 self.name = Tim
    19 self : <class '__main__.Dog'>
    20 self.name = Tim
    21 self : <class '__main__.Dog'>
    22 
    23 实例化出两个对象
    24 False
    25 Tim going to sleep...
    26 False
    27 '''
    实例化多个对象

    2.2 静态方法

     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5 
     6     stat = 'awake'
     7 
     8     def __init__(self):
     9         pass
    10         #print('self.name = %s' %self.name)
    11         #print('self : %s' %type(self))
    12     
    13     @staticmethod
    14     def sleep():
    15         print('going to sleep...')
    16 
    17 print(Dog.stat)
    18 print(Dog().stat)
    19 print(type(Dog.stat))
    20 print(type(Dog().stat))
    21 Dog.sleep()
    22 Dog().sleep()
    23 print(Dog.sleep)
    24 print(Dog().sleep)
    25 print(Dog.sleep is Dog.sleep)
    26 print(Dog().sleep is Dog.sleep)
    27 
    28 '''   
    29 静态方法与类变量性质相似,逻辑上隶属于类,其实独立于类,不受类的影响
    30 awake
    31 awake
    32 <type 'str'>
    33 <type 'str'>
    34 going to sleep...
    35 going to sleep...
    36 <function sleep at 0x7f3f3fb238c0>
    37 <function sleep at 0x7f3f3fb238c0>
    38 True
    39 True
    40 '''
    静态方法与类变量的比较
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5 
     6     def __init__(self, name):
     7         self.name = name
     8         print('self.name = %s' %self.name)
     9     
    10     @staticmethod
    11     def sleep(self):
    12         static_var = 'STATIC'
    13         print('%s is going to sleep...%s' %(self, static_var))
    14 
    15 
    16 Dog('Tim').sleep('Jerry')
    17 print(Dog.sleep('Jerff').static_var)
    18 Dog.sleep('Jerff').static_var = 'Here'
    19 print(Dog.sleep('Jerff').static_var)
    20 
    21 """    
    22 静态方法相当于类变量,是一块代码块逻辑,不存在静态方法内部的调用问题
    23 self.name = Tim
    24 Jerry is going to sleep...STATIC
    25 Jerff is going to sleep...STATIC
    26 Traceback (most recent call last):
    27   File "py_instance.py", line 17, in <module>
    28     print(Dog.sleep('Jerff').static_var)
    29 AttributeError: 'NoneType' object has no attribute 'static_var'
    30 """
    静态方法与中不存在调用关系
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5 
     6     def __init__(self, name):
     7         self.name = name
     8         print('self.name = %s' %self.name)
     9     
    10     @staticmethod
    11     def sleep(self):
    12         print('%s is going to sleep...' %self)
    13 
    14 
    15 Dog('Tim').sleep('Jerry')
    16 print(Dog('Tim').sleep('Jerry') is Dog.sleep('Jerff'))
    17 
    18 
    19 '''  再次证明类与静态方法无关
    20 self.name = Tim
    21 Jerry is going to sleep...
    22 self.name = Tim
    23 Jerry is going to sleep...
    24 Jerff is going to sleep...
    25 True
    26 '''
    静态方法与类
     1 # -*- coding:utf-8 -*-
     2 #
     3 
     4 class Dog(object):
     5     class_var = 'Hrrrrrrrrrrrrr......'
     6 
     7     def __init__(self, name):
     8         self.name = name
     9         print('self.name = %s' %self.name)
    10 
    11     @staticmethod
    12     def sleep(self):
    13         print('%s is going to sleep...' %self)
    14 
    15 
    16 class Animal(Dog):
    17     def sleep(self):
    18         print('%s is here...' %self.name)
    19         print('static method can be overrided by subclass...')
    20 
    21 if __name__ == '__main__':
    22     Dog('Tim').sleep('Jerry')
    23     print(Dog('Tim').sleep('Jerry') is Dog.sleep('Jerff'))
    24     print(Dog.class_var)
    25     Dog.class_var = 'changed......'
    26     print(Dog.class_var)
    27     Animal('Jack').sleep()
    28 
    29 '''   静态方法可以在子类中被重写
    30 self.name = Tim
    31 Jerry is going to sleep...
    32 self.name = Tim
    33 Jerry is going to sleep...
    34 Jerff is going to sleep...
    35 True
    36 Hrrrrrrrrrrrrr......
    37 changed......
    38 self.name = Jack
    39 Jack is here...
    40 static method can be overrided by subclass...
    41 '''    
    静态方法在子类中被重写

    由以上两例可知:

            静态方法仅在逻辑上隶属于类,与类变量性质相当;

            静态方法与类变量一样,执行时只在代码区生成一份,类或多个类实例共享同一个静态方法,相较于实例方法,每生成一个实例,就必须生成一个对象,静态方法更加高效,节约资源;

            静态方法在子类中可被重写,且重写的方法不一定是静态方法。

    2.3 类方法

     1 # -*- coding:utf-8 -*-
     2 #
     3 class Dog(object):
     4 
     5     def __init__(self, name):
     6         self.name = name
     7         print('self.name = %s' %self.name)
     8 
     9     @classmethod
    10     def sleep():
    11         print('%s is going to sleep...' %self)
    12 
    13 print(Dog.sleep)
    14 Dog.sleep()
    15 
    16 ''' 
    17 与实例方法不一样,实例方法的绑定方法是Dog.sleep,类方法绑定的是type.sleep
    18 <bound method type.sleep of <class '__main__.Dog'>>
    19 
    20 类方法默认出入了一个类对象
    21 Traceback (most recent call last):
    22   File "py_instance.py", line 15, in <module>
    23     Dog.sleep()
    24 TypeError: sleep() takes no arguments (1 given)
    25 '''
    类方法绑定的是type类
     1 # -*- coding:utf-8 -*-
     2 #
     3 class Dog(object):
     4 
     5     def __init__(self, name):
     6         self.name = name
     7         print('self.name = %s' %self.name)
     8 
     9     @classmethod
    10     def sleep(name):
    11         print('%s is going to sleep...' %name)
    12 
    13 print(Dog.sleep)
    14 Dog.sleep()
    15 
    16 '''  类对象默认作为第一参数传入到类方法中
    17 <bound method type.sleep of <class '__main__.Dog'>>
    18 <class '__main__.Dog'> is going to sleep...
    19 '''
    类对象作为第一参数传入类方法中
     1 # -*- coding:utf-8 -*-
     2 #
     3 class Dog(object):
     4     
     5     name = 'Here'
     6 
     7     def __init__(self, name):
     8         self.name = name
     9 #       print('self.name = %s' %self.name)
    10 #       print('self = ' %type(self))
    11 
    12     @staticmethod
    13     def talk():
    14         return 'Animals and me' 
    15 
    16     @classmethod
    17     def sleep(cls):
    18         print('%s is going to sleep...' %type(cls))
    19         print('%s is going to sleep...' %cls.name)
    20         print('%s are talking to each other...' %cls.talk())
    21 
    22 print(Dog.sleep)
    23 print(Dog.sleep is Dog.sleep)
    24 Dog('Tim').sleep()
    25 
    26 '''  类方法对类变量和静态方法的调用
    27 <bound method type.sleep of <class '__main__.Dog'>>
    28 False
    29 <type 'type'> is going to sleep...
    30 Here is going to sleep...
    31 Animals and me are talking to each other...
    32 '''
    类方法可以引用类属性和静态方法

    由上面的例子可知:

         类方法的优点参考:http://www.cnblogs.com/ant-colonies/p/6736567.html

    2.4 属性方法

    属性方法的作用就是通过@property把一个方法变成一个静态属性。

    class Dog(object):
     
        def __init__(self,name):
            self.name = name
     
        @property
        def eat(self):
            print(" %s is eating" %self.name)
     
     
    d = Dog("ChenRonghua")
    d.eat()
    

    调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了

    Tim is eating
    Traceback (most recent call last):
      File "py_11.py", line 12, in <module>
        d.eat()
    TypeError: 'NoneType' object is not callable
    

    正确的调用如下:

    d = Dog("ChenRonghua")
    d.eat
     
    输出
    ChenRonghua is eating
    

    好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 以后你会需到很多场景是不能简单通过 定义 静态属性来实现的, 比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:

    1. 连接航空公司API查询

    2. 对查询结果进行解析 

    3. 返回结果给你的用户

    因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以,明白 了么?

     1 # -*- coding:utf-8 -*-
     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 
    10     @property
    11     def flight_status(self):
    12         status = self.checking_status()
    13         if status == 0:
    14             print('flight got canceled...')
    15         elif status == 1:
    16             print('flight has arrived...')
    17         elif status == 2:
    18             print('flight has departured already...')
    19         else:
    20             print('cannot confirm the flight status, check it latter...')
    21 
    22 f = Flight('CA980')
    23 f.flight_status
    24 
    25 '''
    26 checking flight CA980 status
    27 flight has arrived...
    28 '''
    flight_status

    cool , 那现在我只能查询航班状态, 既然这个flight_status已经是个属性了, 那我能否给它赋值呢?试试吧

    f = Flight("CA980")
    f.flight_status
    f.flight_status =  2
    

    输出, 说不能更改这个属性,我擦。。。。,怎么办怎么办。。。

    checking flight CA980 status
    flight has arrived...
    [root@ant-colonies tmp]# python py_flight.py 
    checking flight CA980 status
    flight has arrived...
    Traceback (most recent call last):
      File "py_flight.py", line 24, in <module>
        f.flight_status = 2
    AttributeError: can't set attribute
    

    当然可以改, 不过需要通过@proerty.setter装饰器再装饰一下,此时 你需要写一个新方法, 对这个flight_status进行更改。

     1 # -*- coding:utf-8 -*-
     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 
    10     @property
    11     def flight_status(self):
    12         status = self.checking_status()
    13         if status == 0:
    14             print('flight got canceled...')
    15         elif status == 1:
    16             print('flight has arrived...')
    17         elif status == 2:
    18             print('flight has departured already...')
    19         else:
    20             print('cannot confirm the flight status, check it latter...')
    21 
    22     @flight_status.setter   # modify
    23     def flight_status(self, status):
    24         status_dic = {
    25             0 : 'canceled',
    26             1 : 'arrived',
    27             2 : 'departured'
    28         }
    29         print('33[31;1mHas changed the flight status to %s33[0m' %status_dic.get(status))
    30 
    31     @flight_status.deleter  # delete
    32     def flight_status(self):
    33         print('status has been removed...')
    34 
    35 f = Flight('CA980')
    36 f.flight_status
    37 f.flight_status = 2    # trigger @flight_status.setter
    38 del f.flight_status    # trigger @flight_status.deleter
    modify & delete properties

    输出结果:

    checking flight CA980 status
    flight has arrived...
    Has changed the flight status to departured
    status has been removed...
    

    注意以上代码里还写了一个@flight_status.deleter, 是允许可以将这个属性删除。

     

    总结:

          实例方法通过self访问实例属性    

    def instanceMethod(self, ...):
    

          类方法通过cls方法访问类属性

    @classmethod
    def classMethod(cls, ...):
    

          静态方法,不可访问,可以通过参数传值的方式进行

    @staticmethod
    def staticMethod(*agrs, **kwargs):
    

         属性方法,不可访问,可修改属性和删除属性

    @property
    def propertyMethod(self, ...):
         pass
    
    @propertyMethod.setter
    def propertyMethod(self, ...):
         pass
    
    @propertyMethod.deleter
    def propertyMethod(self, ...):
         pass
    

    实例方法,当类实例化后,实例对象可以访问属性;

    类方法,类对象和实例对象均可访问类属性;

    静态方法,作用域为类中的方法,与类变量类似;

    属性方法,当类实例化后,实例对象可以访问属性,将方法调用方式转变为类变量的访问方式。

     

    3. 类的特殊成员方法

    3.1  __doc__表示类的描述信息

    # -*- coding:utf-8 -*-
    # Author: antcolonies
    
    class Foo(object):
        '''discription of the function of the Foo()'''
    
        def funct(self):
            pass
    
    print(Foo.__doc__)    
    
    输出:
    '''
    discription of the function of the Foo()
    '''
    

    3.2  __module__ 和  __class__ 

      __module__ 表示当前操作的对象在那个模块

      __class__     表示当前操作的对象的类是什么

    1 #!/usr/bin/env python
    2 # -*- coding:utf-8 -*-
    3 # Author: antcolonies
    4 
    5 class C(object):
    6     def __init__(self):
    7         self.name = 'Monkey'
    lib/aa.py
    1 #!/usr/bin/env python
    2 # -*- coding:utf-8 -*-
    3 # Author: antcolonies
    4 
    5 from lib.aa import C
    6 
    7 obj = C()
    8 print(obj.__module__)   # lib.aa
    9 print(obj.__class__)    # <class 'lib.aa.C'>
    index.py

    3.3  __init__ 构造方法,通过类创建对象时,自动触发执行。

    3.4  __del__

     析构方法,当对象在内存中被释放时,自动触发执行。

    注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,
        因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的.
    

    3.5  __call__ 对象后面加括号,触发执行

    注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
    class Foo(object):
        def __init__(self):
            pass
        def __call__(self, *args, **kwargs):
            print('__call__')
    
    obj = Foo()   # 执行__init__
    obj()         # 执行__call__
    

    3.6. __dict__ 查看类或对象中的所有成员新式类__slots__内置属性对__dict__属性的消除作用

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: antcolonies
    
    class Province(object):
        country = 'China'
        def __init__(self, name, count):
            self.name = name
            self.count = count
        def func(self, *args, **kwargs):
            print('func')
    
    # 获取类成员,即:静态字段、方法
    print(Province.__dict__)
    # {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Province' objects>, 
    # '__doc__': None, 'country': 'China', 'func': <function Province.func at 0x00000000027ECA60>, 
    # '__init__': <function Province.__init__ at 0x00000000027EC8C8>, '__weakref__': <attribute '__weakref__' of 'Province' objects>}
    
    # 获取对象obj_1的成员
    obj_1 = Province('Hebei', 10000)
    print(obj_1.__dict__)
    # {'name': 'Hebei', 'count': 10000}
    
    # 获取对象obj_2的成员
    obj_2 = Province('Henan', 30009)
    print(obj_2.__dict__)
    # {'name': 'Henan', 'count': 30009}
    

    3.7  __str__ ,如果一个类中定义了__str__方法,那么在打印实例化对象时,默认输出该__str__方法的返回值。

    class Foo(object):
        def method(self):
            print('----------')
    
        def __str__(self):
            return 'Alex Lee'
    
    
    obj = Foo()
    print(obj)
    
    '''Alex Lee'''
    

    3.8  __getitem__、__setitem__、__delitem__

    用于索引操作,如字典。以上分别表示获取、设置、删除数据

    # -*- coding:utf-8 -*-
    # Author: antcolonies
    
    class Foo(object):
        def __getitem__(self, item):
            print('__getitem', item)
    
        def __setitem__(self, key, value):
            print('__setitem__',key, value)
    
        def __delitem__(self, key):
            print('__delitem__', key)
    
    obj = Foo()
    
    result = obj['k1']      # trigger and run __getitem__
    obj['k2'] = 'alex'      # trigger and run __settitem__
    del obj['k1']
    
    '''
    __getitem k1
    __setitem__ k2 alex
    __delitem__ k1
    '''
    

    3.9  __new__ __metaclass__

    参考: http://www.cnblogs.com/ant-colonies/p/6747309.html

             http://www.cnblogs.com/ant-colonies/p/6748064.html

    类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__

     

    4. 反射

     参考:http://www.cnblogs.com/ant-colonies/p/6756014.html

             http://www.cnblogs.com/ant-colonies/p/6758266.html

     

    5. 异常处理

    5.1 异常基础

    在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是出现一个提示的页面。

    try:
        pass
    except Exception as e:
        pass
    

    需求:将用户输入的两个数字相加

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author: antcolonies
     4 
     5 while True:
     6     num_1 = input('num_1: ')
     7     num_2 = input('num_2: ')
     8     try:
     9         num_1 = int(num_1)
    10         num_2 = int(num_2)
    11         result = num_1 + num_2
    12     except Exception as e:
    13         print('error message: %s' %e)
    exception

    5.2 异常的种类

    python中的异常种类非常多,每个异常专门用于处理某一项异常。

     1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
     2 FileNotFoundError 输入/输出异常;基本上是无法打开文件
     3 ImportError 无法引入模块或包;基本上是路径问题或名称错误
     4 IndentationError 语法错误(的子类) ;代码没有正确对齐
     5 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
     6 KeyError 试图访问字典里不存在的键
     7 KeyboardInterrupt Ctrl+C被按下
     8 NameError 使用一个还未被赋予对象的变量
     9 SyntaxError Python代码非法,代码不能编译
    10 TypeError 传入对象类型与要求的不符合
    11 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
    12 ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    常见异常类型
     1 ArithmeticError
     2 AssertionError
     3 AttributeError
     4 BaseException
     5 BufferError
     6 BytesWarning
     7 DeprecationWarning
     8 EnvironmentError
     9 EOFError
    10 Exception
    11 FloatingPointError
    12 FutureWarning
    13 GeneratorExit
    14 ImportError
    15 ImportWarning
    16 IndentationError
    17 IndexError
    18 IOError
    19 KeyboardInterrupt
    20 KeyError
    21 LookupError
    22 MemoryError
    23 NameError
    24 NotImplementedError
    25 OSError
    26 OverflowError
    27 PendingDeprecationWarning
    28 ReferenceError
    29 RuntimeError
    30 RuntimeWarning
    31 StandardError
    32 StopIteration
    33 SyntaxError
    34 SyntaxWarning
    35 SystemError
    36 SystemExit
    37 TabError
    38 TypeError
    39 UnboundLocalError
    40 UnicodeDecodeError
    41 UnicodeEncodeError
    42 UnicodeError
    43 UnicodeTranslateError
    44 UnicodeWarning
    45 UserWarning
    46 ValueError
    47 Warning
    48 ZeroDivisionError
    更多异常类型
    1 dic = ['Tim', 'Cook']
    2 try:
    3     dic[10]
    4 except IndexError as e:
    5     print('error message: %s' %e)
    实例:IndexError
    1 dic = {'k1':'v1'}
    2 try:
    3     dic['k2']
    4 except KeyError as e:
    5     print('error message: %s' %e)
    实例:KeyError
    1 s1 = 'Hello'
    2 try:
    3     int(s1)
    4 except ValueError as e:
    5     print('error message: %s' %e)
    实例:ValueError

    对于上述实例,异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。

    # 未捕获到异常,程序直接报错
     
    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    

    所以,写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    except KeyError as e:
        print(e)
    except ValueError as e:
        print(e)
    

    在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即:

    s1 = 'hello'
    try:
        int(s1)
    except Exception as e:
        print(e)
    

    接下来你可能要问了,既然有这个万能异常,其他异常是不是就可以忽略了!

    答:当然不是,对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行。

    s1 = 'hello'
    try:
        int(s1)
    except KeyError as e:
        print('键错误') 
    except IndexError as e:
        print('索引错误')
    except Exception as e:
        print('错误')
    

    5.3 异常的其他结构

    try:
        # 主代码块
        pass
    except KeyError as e:
        # 异常时,执行该块
        pass
    else:
        # 主代码块执行完,执行该块
        pass
    finally:
        # 无论异常与否,最终执行该块
        pass
    
     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author: antcolonies
     4 
     5 names = ['alex', 'jack']
     6 data = {}
     7 
     8 
     9 try:
    10     names[3]
    11     data['name']
    12     open('test.tc')
    13     names[1]
    14 except FileNotFoundError as e:
    15     print(e)
    16 except KeyError as e:
    17     print('%s does not exist' %e)
    18 except IndexError as e:
    19     print(e)
    20 # except (IndexError,KeyError) as e:      不同错误的相同处理方式
    21 #     print(e)
    22 except Exception as e:           # 抓取所有错误,一般用于错误抓取末尾
    23     print('all error can be catched %s' %e)
    24 else:
    25     print('all things are okay now!')
    26 finally:
    27     print('all can be done, no matter what runs wrong')
    实例

    5.5 自定义异常

    class CustomizeError(Exception):
        def __init__(self, msg):
            self.msg = msg
        def __str__(self):
            return self.msg
    
    try:
        name = []
        raise CustomizeError('Database Connection error.. ')
    except CustomizeError as e:
        print(e)
    
     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author: antcolonies
     4 
     5 
     6 class IndexError(Exception):
     7     def __init__(self, msg):
     8         self.msg = msg
     9     def __str__(self):
    10         return self.msg
    11 
    12 try:
    13     name = []
    14     # name[3]
    15     raise IndexError('Database Connection error.. ')
    16 except IndexError as e:
    17     print(e)
    重载系统默认错误类型

    5.6 断言(assert)

    在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误)。这时候断言assert 就显得非常有用。

    assert的语法格式:

    assert expression
    

    它的等价语句为:

    if not expression:
        raise AssertionError
    

    这段代码用来检测数据类型的断言,因为 a_strstr 类型,所以认为它是 int 类型肯定会引发错误。

    >>> a_str = 'this is a string'
    >>> type(a_str)
    <type 'str'>
    >>> assert type(a_str)== str
    >>> assert type(a_str)== int
    
    Traceback (most recent call last):
      File "<pyshell#41>", line 1, in <module>
        assert type(a_str)== int
    AssertionError
    

     

    参考: http://www.cnblogs.com/wupeiqi/p/4493506.html

               http://www.cnblogs.com/wupeiqi/p/4766801.html

     

  • 相关阅读:
    kafka 幂等生产者及事务(kafka0.11之后版本新特性)
    git 忽略 .idea文件
    Java Scala 混合编程导致 编译失败 ,【找不到符号】问题解决
    Starting sshd: /var/empty/sshd must be owned by root and not group or world-writable.
    Spark RDD持久化、广播变量和累加器
    PSQLException: FATAL: no pg_hba.conf entry for host "127.0.0.1", user "ambari", database "ambari", SSL off
    PostgreSQL:Java使用CopyManager实现客户端文件COPY导入
    ThreadLocal的使用及原理分析
    gradlew和gradle的区别
    Managing Large State in Apache Flink®: An Intro to Incremental Checkpointing
  • 原文地址:https://www.cnblogs.com/ant-colonies/p/6726257.html
Copyright © 2011-2022 走看看