• 异常 反射


    一、异常处理:

     1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
     2 IOError 输入/输出异常;基本上是无法打开文件
     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 导致你以为正在访问它
    13 ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    14 
    15 常用异常
    常用异常
     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
    49 
    50 更多异常
    更多异常
    1  try:
    2      intput = raw_input()
    3      data = int(intput)
    4  except Exception,e:  #e是Exception类的一个对象,调用__str__方法
    5 print"请输入数字"
     1 #输出sb,输出A类的__str__方法
     2 
     3 class A:
     4     def __str__(self):
     5         return 'sb'
     6 obj = A()
     7 print obj
     8 
     9 #自定义错误异常
    10 
    11 class AlexError(Exception):
    12     def __init__(self,msg=None):
    13         self.message = msg
    14     def __str__(self):
    15         if self.message:
    16             return self.message
    17         else:
    18             return 'alex error'
    19 try:
    20     raise AlexError('error')    #当有值时,输出值,否则输出alex erroer
    21 except Exception,e:
    22     print e
    自定义异常

    二、反射:

     1 helpper.py    #模块
     2 -----------------------------------------------
     3 def dev():
     4     return "home dev"
     5 def index():
     6     return "home index"
     7 
     8 
     9 index.py     #模块
    10 -----------------------------------------------
    11 import helpper
    12 
    13 url = raw_input('url:')      #输入helpper/dev
    14 
    15 if url == "helpper/dev":
    16     ret = helpper.dev()
    17     print ret
    18 elif url == "helpper/index":
    19     ret = helpper.index()
    20     print ret
    Example
     1 helpper.py    #模块
     2 -----------------------------------------------
     3 def dev():
     4     return "home dev"
     5 def index():
     6     return "home index"
     7 
     8 
     9 index.py     #模块
    10 -----------------------------------------------
    11 import helpper
    12 
    13 url = raw_input('url:')  #输入helpper/dev
    14 controller,action = url.split('/')
    15 func = getattr(helpper,action)
    16 ret = func()
    17 print ret
    Example 进阶
     1 helpper.py   #模块
     2 --------------------------------------------
     3 def dev():
     4     return "home dev"
     5 def index():
     6     return "home index"
     7 
     8 
     9 
    10 index.py    #模块
    11 ---------------------------------------------
    12 controller,action = raw_input("url:").split('/')
    13 model = __import__(controller)
    14 
    15 func = getattr(model,action)
    16 ret = func()
    17 print ret
    __import__和反射 getattr

    二、反射(2):

     1 import sys
     2 
     3 class WebServer(object):
     4     def __init__(self,host,port):
     5         self.host = host
     6         self.port = port
     7     def start(self):
     8         print("Server is starting...")
     9     def stop(self):
    10         print("Server is stopping...")
    11     def restart(self):
    12         self.stop()
    13         self.start()
    14 if __name__ == "__main__":
    15     obj = WebServer('localhost','3306')
    16     if sys.argv[1] == "start":
    17         obj.start()
    example
    import sys
    
    class WebServer(object):
        def __init__(self,host,port):
            self.host = host
            self.port = port
        def start(self):
            print("Server is starting...")
        def stop(self):
            print("Server is stopping...")
        def restart(self):
            self.stop()
            self.start()
    if __name__ == "__main__":
        obj = WebServer('localhost','3306')
        cmd_list = {
            'start':obj.start,
            'stop':obj.stop
        }
        if sys.argv[1] in cmd_list:
            cmd_list[sys.argv[1]]()
    example 字典形式
     1 import sys
     2 
     3 class WebServer(object):
     4     def __init__(self,host,port):
     5         self.host = host
     6         self.port = port
     7     def start(self):
     8         print("Server is starting...")
     9     def stop(self):
    10         print("Server is stopping...")
    11     def restart(self):
    12         self.stop()
    13         self.start()
    14 if __name__ == "__main__":
    15     obj = WebServer('localhost','3306')
    16     if hasattr(obj,sys.argv[1]):
    17         func = getattr(obj,sys.argv[1])  #获取obj.start 的内存地址
    18         func()
    example 进阶hasattr  getattr
     1 import sys
     2 
     3 class WebServer(object):
     4     def __init__(self,host,port):
     5         self.host = host
     6         self.port = port
     7     def start(self):
     8         print("Server is starting...")
     9     def stop(self):
    10         print("Server is stopping...")
    11     def restart(self):
    12         self.stop()
    13         self.start()
    14 
    15 def test_run(name):
    16     print("running..",name)
    17 
    18 if __name__ == "__main__":
    19     obj = WebServer('localhost','3306')
    20     if hasattr(obj,sys.argv[1]):
    21         func = getattr(obj,sys.argv[1])  #获取obj.start 的内存地址
    22         func()
    23     setattr(obj,"run",test_run)
    24     obj.run('xxx')
    25 
    26 ----------------------------------------------------------------------
    27 
    28 #/usr/bin/env python
    29 # -*- coding:utf-8 -*-
    30 
    31 import sys
    32 
    33 class WebServer(object):
    34     def __init__(self,host,port):
    35         self.host = host
    36         self.port = port
    37     def start(self):
    38         print("Server is starting...")
    39     def stop(self):
    40         print("Server is stopping...")
    41     def restart(self):
    42         self.stop()
    43         self.start()
    44 
    45 def test_run(self,name):
    46     print("running..",name,self.host)
    47 
    48 if __name__ == "__main__":
    49     obj = WebServer('localhost','3306')
    50     if hasattr(obj,sys.argv[1]):
    51         func = getattr(obj,sys.argv[1])  #获取obj.start 的内存地址
    52         func()
    53     setattr(obj,"run",test_run)
    54     obj.run(obj,'xxx')
    setattr

    三、设计模式:

     1 class SqlHelper:
     2 
     3     __static_instance = None
     4 
     5     def __init__(self):
     6         self.hostname = '0.0.0.0'
     7         self.port = 3306
     8         self.user = 'root'
     9         self.passd = '123'
    10 
    11     @classmethod
    12     def instance(cls):
    13         if cls.__static_instance:
    14             return cls.__static_instance
    15         else:
    16             cls.__static_instance = SqlHelper()
    17             return cls.__static_instance
    18 
    19     def fetch(self):
    20         pass
    21     def remove(self):
    22         pass
    23 
    24 def add_user():
    25     obj = SqlHelper.instance()
    26     obj.fetch()
    27 
    28 def del_user():
    29     obj = SqlHelper.instance()
    30     obj.remove()
    31 
    32 print id(SqlHelper.instance())
    33 print id(SqlHelper.instance())
    单例模式一

                                                                                                                                   ----根据武沛齐----整理修改-----

  • 相关阅读:
    OSGI简介
    公司僵尸帐号引发了一系列的入侵事件-细说密码强度验证的重要性
    为其他对象提供一种代理以控制对这个对象的访问-代理模式
    运用共享技术有效地支持大量细粒度的对象-享元模式
    移动APP为什么要开发两套Android和IOS-桥接模式
    非法疫苗引发的思考 -外观模式
    你们还记得张江男、张江女两张图片吗?-装饰模式
    一个程序员的蜕变(我是如何成为架构师的)
    公司新加了一台友宝自动售货机引发的思考-适配器模式
    程序员如何应对北上广高房价示例解说-建造者模式
  • 原文地址:https://www.cnblogs.com/golangav/p/6150186.html
Copyright © 2020-2023  润新知