面向对像及其他

其他相关

1、isinstance(obj,cls)

      检查是否obj是类cls的对象

# 针对变量 n = 123

s 
= "123" print isinstance(n,int) # True print isinstance(s,int) # False print isinstance(s,str) # False

#
针对类 class Foo: pass

obj 
= Foo() print isinstance(obj,Foo) # True

2、issubclass(sub,super)

      检查sub类是否是super类的派生类

class
Foo: pass class Fun(Foo): pass print issubclass(Fun,Foo) # True

3、异常处理

1:模式:
try:
# 正常的代码
   
pass
except
Exception
,e:
    # 异常后显示的内容
   
pass

e是包含在Exception类中的一个对象,其中包含所有的报错的情况

实例:

while
True: num1 = raw_input('num1:') num2 = raw_input('num2:') try: num1 = int(num1) num2 = int(num2) result = num1 + num2 except Exception,e: print "报错信息如下显示:" print e '''

打印结果:
num1:3
num2:f
报错信息如下显示:
invalid literal for int() with base 10: 'f'
'''

如果对程序的要求没有特殊的异常处理可以直接使用总的Exception,如果单独处理某种错误,可以按照下面的方法操作

try

:
li = [11,22,33,44]
li[110]
except IndexError,e:
print e

这样就只对索引的错误进行异常处理。

2:异常的种类

异常的种类有很多,每个异常专门用于处理某一项异常。

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

异常其他结构

try

:
# 主代码块
pass
except
KeyError
,e:
# 异常时,执行该块
pass
else
:
# 主代码块执行完执行该块
pass
finally
:
# 无论是否异常,最终执行该块

pass

主动触发异常

try:
    N = raw_input("请输入1:")
    if N == 1:
        print "成功"
    else:
         raise Exception('我这里出错了。。。')
except Exception,e:
    print "显示错误页面。。。。"
    print e

打印结果:
请输入1:2
显示错误页面。。。。
我这里出错了。。。

自定义触发异常

class Alexerror(Exception):
    def __init__(self,msg=None):
        self.message = msg
    def __str__(self):
        if self.message:
            return self.message
        else:
            return 'Alex Error'
try:
    #raise Alexerror('报错了报错了')
    raise Alexerror()
except Exception,e:
    print e

当类Alexerror加上括号执行的时候,是执行类中的构造函数__init__

Exception函数在返回的时候,是将__str__中的字符串返回出来。

如果使用Alexerror来执行的话,就返回Alex Error,在括号中加入内容的话,就返回其中的内容。

4、反射

普通方式实现:

首先在主程序中实现:

import home
print "oldboy 框架"
url = raw_input("请输入URL:")
if url == "home/func1":
    ret = home.func1()
    print ret
elif url == "home/func1":
    ret = home.func1()
    print ret
elif url == "home/func1":
    ret = home.func1()
    print ret
elif url == "home/func1":
    ret = home.func1()
    print ret
else:
    print "页面404错误"

调用的页面程序

#!/usr/bin/env python
# coding:utf-8
def func1():
    return "result func1"
def func2():
    return "result func2"
def func3():
    return "result func3"
def func4():
    return "result func4"

实现结果

oldboy 框架
请输入URL:rtew
页面404错误
oldboy 框架
请输入URL:home/func1
result func1

部分反射

import home
print "oldboy 框架"
url = raw_input("请输入URL:")
controller,action = url.split('/')
func = getattr(home,action)
ret = func()
print ret

打印结果:
oldboy 框架
请输入URL:home/func1
result func1

action = 字符串

getattr:去某个容器模块中找函数,字符串函数名,如果有则获取函数。

以字符串的形式执行某一个模块中的函数

反射功能由以下四个内置函数提供:

hasattr  getattr  setattr   delattr  这四个函数分别用于对对象内部执行:检查是否含有某个成员、获取成员、设置成员、删除成员。

# 操作内存中某个容器中的元素
# getattr setattr delattr hasattr

# 找到home文件将内容加载到内存
import home
# 列出home中的所有内容
print dir(home)
print hasattr(home,'func1')
print hasattr(home,'2231241')

print getattr(home,'func2')

setattr(home,'alex',lambda x:x+1)
print dir(home)

delattr(home,'func3')
print dir(home)


class foo:
    static_name = 'cgt'
    def __init__(self):
        self.name = 'cgt'

    def show(self):
        pass
    @staticmethod
    def static_show():
        pass

    @classmethod
    def class_show(cls):
        pass


print foo.__dict__.keys()

print hasattr(foo,'show')

obj = foo()
print obj.__dict__
# 查看对象obj中有没有name元素,
print hasattr(obj,'name')
print hasattr(obj,'show')



打印结果:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func1', 'func2', 'func3', 'func4']
True
False
<function func2 at 0x021878F0>
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'alex', 'func1', 'func2', 'func3', 'func4']
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'alex', 'func1', 'func2', 'func4']
['static_show', '__module__', 'show', 'static_name', 'class_show', '__doc__', '__init__']
True
{'name': 'cgt'}
True
True

设计模式

1、单例,顾名思义单个实例。

比如在游戏的场景中,就无法使用单例模式,要不你怎么创建那么多角色。

实际应用:

#!/usr/bin/env python
# coding:utf-8
class SqlHelper:
    __static_instance = None

    def __init__(self):
        pass

    @classmethod
    def instance(cls):
        if cls.__static_instance:
            return cls.__static_instance
        else:
            cls.__static_instance = SqlHelper()
            return cls.__static_instance

    def fetch(self):
        pass

    def remove(self):
        pass


def get_user():
    obj = SqlHelper.instance()
    obj.fetch()
    print id(obj)
    return '1'

def del_user():
    obj = SqlHelper.instance()
    obj.remove()
    return '1'

借助web来实现

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from wsgiref.simple_server import make_server

def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    url = environ['PATH_INFO']
    # 对URL以/进行分割,
    # http://localhost:8001/func3
    # temp = func3
    filename = url.split('/')[1]
    mothodname = url.split('/')[2]
    # import home
    module = __import__(filename)


    # 去home中检查,是否含有指定的函数
    is_exist = hasattr(module, mothodname)
    if is_exist:
        # 获取函数
        func = getattr(module, mothodname)
        # 执行t函数,并获取返回值
        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()

简单举例:

class SqlHelper:
    __static_instance = None

    def __init__(self):
        self.hostname = '0.0.0.0'
        self.port = 3306

    @classmethod
    def instance(cls):
        if cls.__static_instance:
            return cls.__static_instance
        else:
            cls.__static_instance = SqlHelper()
            return cls.__static_instance



obj1 = SqlHelper.instance()
print id(obj1)
obj2 = SqlHelper.instance()
print id(obj2)

 

原文地址:https://www.cnblogs.com/caoxiaojian/p/5055533.html