• 面向对象及其相关


    面向对象及其相关:

    面向对象基础篇可以参考:

    [初识面向对象编程] http://www.cnblogs.com/yangyinghua/p/5020914.html

    [面向对象的三大特性介绍] http://www.cnblogs.com/yangyinghua/p/5024892.html

    [面向对象之类成员] http://www.cnblogs.com/yangyinghua/p/5041640.html

    相关知识点:

    isinstance(obj,cls)
    检查obj是否是类cls的对象

    >>> num1 = 10
    >>> nmu2 = 20
    >>>
    >>> isinstance(num1,int) 
    True
    
    >>> str1 = 'abc'
    >>> isinstance(str1,str)
    True
    
    
    class A:
        pass
    class B(A):
        pass
    
    b = B()
    print isinstance(b,A) 
    
    

    issubclass(sub, super)
    检查sub类是否是 super 类的派生类

    class A(object):
        pass
    
    class B(A):
        pass
    
    print issubclass(B, A)
    

    一、异常处理:

    try:
    	 #正常代码逻辑块
        user_input = int(raw_input('请输入数字:').strip())
    except Exception,e:
    	 #逻辑代码块出现错误
        print "error:",e
        # 日志,错误详细,e,e中封装了上面出现的错误
        
    try:
        user_input = int(raw_input('请输入数字:').strip())
    except Exception,e:
        print "输入错误,请输入数字"
        
    
    python中还有很多Error类型:

    以下是几种比较常见的异常类型:

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    导致你以为正在访问它
    ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    
    

    异常捕获

    捕获:IndexError 实例:

    try:
    	li = ['a','b','c']
    	print li[10]
    except IndexError,e:
        print "不存在这个下标,索引"
        print "异常报错信息:",e
    

    执行结果:

    不存在这个下标,索引
    异常报错信息: list index out of range
    

    万能异常:

    li = ['a','b','c']
    try:
        li[10]
    except IndexError,e:
        print "不存在这个下标,索引"
        print "异常报错信息:",e
    except Exception,e: #(当所有的异常捕获完之后,最后为了保证程序正常运行,这里可以在最后加一个万能异常,相当于最后一道防护线)
        print e
    

    知识点:
    IndexError 等这些异常,都是Exception的派生类

    主动触发异常:

    try:
        raise Exception('错误了。。。')
    except Exception,e:
        print e
    

    知识点1,请注意:

    try:
        pass  
        # 比如这里是连接数据库进行相关操作
    except IndexError,e:
        pass
    except Exception,e:
        pass
    else:
        pass
        #逻辑块出现异常
    finally:  #不管上面的执行正确与否,最终需要执行
        #上面执行完后,需要断开数据库,就可以在这里操作
        pass
    

    知识点2:

    try:
        user_input = int(raw_input('请输入数字:').strip())
    except Exception,e:
    	    print "error:",e
            # e,调用的是Exception中__str__ 方法   
    

    例子:

    class Derror(Exception):
        def __str__(self):
            return 'Derror error'
    
    try:
        raise Derror('错误')
    except Exception,e:
        print e
    

    自定义异常

    class Derror(Exception):
        def __init__(self,msg):
            self.Message = msg
    
        def __str__(self):
            if self.Message:
                return self.Message
            else:
                return 'Derror error'
    
    try:
        raise Derror('错误了,你快看看吧~')
    except Derror,e:
        print e
    
    

    执行结果:

    错误了,你快看看吧~
    

    二、断言

    assert +条件 #用途,程序调试

    assert 1 == 1  # 如果1等于1,正确,什么也不执行,否则,报异常
    

    三、反射

    python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

    直接看代码:

    home.py

    
    def login():
        return "welcome to login mysite"
    
    def logout():
        return "logout..."
    
    def shows():
        return "shows"
    
    def watch():
        return "watch"
    
    def buy():
        return "buy"
    

    方式一:

    index.py

    url = raw_input('请输入url:').strip()
    if url == 'home/login':
        result = home.login()
        print result
    elif url == 'home/logout':
        result = home.logout()
        print result
    elif url == 'home/shows':
        result = home.shows()
        print result
    elif url == 'home/watch':
        result = home.watch()
        print result
    elif url == 'home/buy':
        result = home.buy()
        print result
    else:
        print '404 not found'
    
    

    执行结果:

    请输入url:home/buy
    buy
    

    方式二:
    通过getattr执行:

    url = raw_input('请输入url:').strip()
    controller,action = url.split('/')
    
    func = getattr(home,action)
    
    result = func()
    
    print result
    

    执行结果:

    请输入url:home/buy
    buy
    

    先看下面的例子:(经典例子)

    webindex.py

    from wsgiref.simple_server import make_server
    
    def RunServer(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        url = environ['PATH_INFO']
        temp = url.split('/')[1]        # localhost:8001/login 得到第一个元素:login
        import home
         
        is_exist = hasattr(home, temp)  # 去home模块中检查,是否含有指定函数
        if is_exist:  #如果存在指定的函数
            func = getattr(home, temp)  # 获取函数并获取返回值
            ret = func()
            return ret                  # 将函数返回值响应给请求者(我们下面用浏览器请求)
        else:
            return '404 not found'
    
    if __name__ == '__main__':
        httpd = make_server('', 8001, RunServer)
        print "Serving HTTP on port 8001..."
        httpd.serve_forever()
    

    执行:

    Serving HTTP on port 8001...
    127.0.0.1 - - [13/Dec/2015 14:38:01] "GET /login/login HTTP/1.1" 200 23
    127.0.0.1 - - [13/Dec/2015 14:38:01] "GET /favicon.ico HTTP/1.1" 200 13
    

    然后后浏览器执行:

    http://localhost:8001/login/login
    

    输出结果:

    welcome to login mysite
    

    setattr: 设置成员

    print dir(home)
    
    setattr(home,'allen','good job')    #‘good job’这里也可以是函数,如下:
    
    print dir(home)
    
    setattr(home,'allen',lambda x:x+1)  #设置成员
    
    print dir(home)
    
    delattr(home,'login')               #删除成员
    
    print dir(home)
    

    执行结果如下:

    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'buy', 'login', 'logout', 'shows', 'watch']
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'allen', 'buy', 'login', 'logout', 'shows', 'watch']
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'allen', 'buy', 'login', 'logout', 'shows', 'watch']
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'allen', 'buy', 'logout', 'shows', 'watch']
    

    hasattr: 检查是否含有成员

    class Person(object):
        country = 'china'
    
        def __init__(self):
            self.name = 'allen'
    
        def hand(self):
            print "This is my hand"
    
        @staticmethod
        def head(self):
            print "This is my head"
    
        @classmethod
        def foot(self):
            print "This is my foot"
    
    print "===== Person ============"
    print Person.__dict__
    print Person.__dict__.values()
    
    print hasattr(Person,'country')
    
    print "==== P1 ================="
    P1 = Person()
    print P1.__dict__  
    print P1.__dict__.values()
    
    print hasattr(P1,'name')
    print hasattr(P1,'hand')
    

    执行结果如下:

    ===== Person ============
    {'__dict__': <attribute '__dict__' of 'Person' objects>, '__module__': '__main__', '__doc__': None, 'foot': <classmethod object at 0x109c3e520>, 'country': 'china', '__weakref__': <attribute '__weakref__' of 'Person' objects>, 'head': <staticmethod object at 0x109c3e4e8>, '__init__': <function __init__ at 0x109c40c80>, 'hand': <function hand at 0x109c40cf8>}
    [<attribute '__dict__' of 'Person' objects>, '__main__', None, <classmethod object at 0x109c3e520>, 'china', <attribute '__weakref__' of 'Person' objects>, <staticmethod object at 0x109c3e4e8>, <function __init__ at 0x109c40c80>, <function hand at 0x109c40cf8>]
    True
    ==== P1 =================
    {'name': 'allen'}
    ['allen']
    True
    True
    

    home/login 前面讲的都是login

    下面讲讲home (提示:路由系统就是基于这个做的,我指的是其中一部分实现)

    import home #下面的方面更吊,简直碉堡了,而且不需要使用import的方法,直接动态导入
    
    module = __import__('home')
    
    controller,action = raw_input("请输入:").split('/')
    module = __import__(controller)
    func = getattr(module,action)
    result = func()
    print result
    

    执行结果:

    请输入:home/login
    welcome to login mysite
    

    关于设计模式,将在之后详细介绍

    更多连接:http://www.cnblogs.com/wupeiqi/articles/5017742.html

  • 相关阅读:
    jstl插件使用
    IDEA配置tomcat
    Spring框架
    2020/7/17 JAVA模拟斗地主发牌洗牌
    2020/7/15 JAVA之Map接口
    2020/7/14 Java之增强for循环、泛型、List接口、Set接口
    2020/7/13 集合之ArrayList集合、Collection接口、Iterator迭代器
    2020/7/13 常用API之基本类型包装类、System类、Math类、Arrays类、大数据运算
    2020/7/11 日期相关类
    2020/7/8 JAVA总结之:匿名对象/内部类/包的声明与访问/访问修饰符/代码块
  • 原文地址:https://www.cnblogs.com/yangyinghua/p/5059102.html
Copyright © 2020-2023  润新知