python——面向对象相关,,其他相关一、isin


其他相关

一、isinstance(obj, cls)

检查是否obj是否是类 cls 的对象

123456classFoo(object):passobj=Foo()isinstance(obj, Foo)

二、issubclass(sub, super)

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

1234567classFoo(object):passclassBar(Foo):passissubclass(Bar, Foo)

三、异常处理

1、异常基础

在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!!

1234try:passexceptException,ex:pass

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

技术分享
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
View Code

2、异常种类

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

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

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

1234567# 未捕获到异常,程序直接报错s1=‘hello‘try:int(s1)exceptIndexError,e:printe

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

123456789s1=‘hello‘try:int(s1)exceptIndexError,e:printeexceptKeyError,e:printeexceptValueError,e:printe

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

12345s1=‘hello‘try:int(s1)exceptException,e:printe

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

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

123456789s1=‘hello‘try:int(s1)exceptKeyError,e:print‘键错误‘exceptIndexError,e:print‘索引错误‘exceptException, e:print‘错误‘

3、异常其他结构

123456789101112try:# 主代码块passexceptKeyError,e:# 异常时,执行该块passelse:# 主代码块执行完,执行该块passfinally:# 无论异常与否,最终执行该块pass

4、主动触发异常

1234try:raiseException(‘错误了。。。‘)exceptException,e:printe

5、自定义异常

123456789101112classWupeiqiException(Exception):def__init__(self, msg):self.message=msgdef__str__(self):returnself.messagetry:raiseWupeiqiException(‘我的异常‘)exceptWupeiqiException,e:printe

6、断言

12345# assert 条件assert1==1assert1==2

四、反射

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

class Foo(object):     def __init__(self):        self.name = ‘wupeiqi‘     def func(self):        return ‘func‘ obj = Foo() # #### 检查是否含有成员 ####hasattr(obj, ‘name‘)hasattr(obj, ‘func‘) # #### 获取成员 ####getattr(obj, ‘name‘)getattr(obj, ‘func‘) # #### 设置成员 ####setattr(obj, ‘age‘, 18)setattr(obj, ‘show‘, lambda num: num + 1) # #### 删除成员 ####delattr(obj, ‘name‘)delattr(obj, ‘func‘)

详细解析:

当我们要访问一个对象的成员时,应该是这样操作:

1234567891011121314classFoo(object):def__init__(self):self.name=‘alex‘deffunc(self):return‘func‘obj=Foo()# 访问字段obj.name# 执行方法obj.func()
技术分享那么问题来了?a、上述访问对象成员的 name 和 func 是什么?答:是变量名b、obj.xxx 是什么意思?答:obj.xxx 表示去obj中或类中寻找变量名 xxx,并获取对应内存地址中的内容。c、需求:请使用其他方式获取obj对象中的name变量指向内存中的值 “alex”技术分享
class Foo(object):     def __init__(self):        self.name = ‘alex‘ # 不允许使用 obj.nameobj = Foo()
技术分享
class Foo(object):    def __init__(self):        self.name = ‘alex‘    def func(self):        return ‘func‘# 不允许使用 obj.nameobj = Foo()print obj.__dict__[‘name‘]
方式一技术分享
class Foo(object):    def __init__(self):        self.name = ‘alex‘    def func(self):        return ‘func‘# 不允许使用 obj.nameobj = Foo()print getattr(obj, ‘name‘)
方式二

d、比较三种访问方式

obj.nameobj.__dict__[‘name‘]getattr(obj, ‘name‘)

答:第一种和其他种比,...
第二种和第三种比,...

技术分享
#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverclass Handler(object):    def index(self):        return ‘index‘    def news(self):        return ‘news‘def RunServer(environ, start_response):    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])    url = environ[‘PATH_INFO‘]    temp = url.split(‘/‘)[1]    obj = Handler()    is_exist = hasattr(obj, temp)    if is_exist:        func = getattr(obj, temp)        ret = func()        return ret    else:        return ‘404 not found‘if __name__ == ‘__main__‘:    httpd = make_server(‘‘, 8001, RunServer)    print "Serving HTTP on port 8000..."    httpd.serve_forever()
Web框架实例

结论:反射是通过字符串的形式操作对象相关的成员。一切事物都是对象!!!

技术分享
#!/usr/bin/env python# -*- coding:utf-8 -*-import sysdef s1():    print ‘s1‘def s2():    print ‘s2‘this_module = sys.modules[__name__]hasattr(this_module, ‘s1‘)getattr(this_module, ‘s2‘)
反射当前模块成员

类也是对象

1234567891011121314151617classFoo(object):staticField="old boy"def__init__(self):self.name=‘wupeiqi‘deffunc(self):return‘func‘@staticmethoddefbar():return‘bar‘printgetattr(Foo,‘staticField‘)printgetattr(Foo,‘func‘)printgetattr(Foo,‘bar‘)

模块也是对象

技术分享
#!/usr/bin/env python# -*- coding:utf-8 -*-def dev():    return ‘dev‘
home.py
12345678910111213141516171819#!/usr/bin/env python# -*- coding:utf-8 -*-"""程序目录:home.pyindex.py当前文件:index.py"""importhome as obj#obj.dev()func=getattr(obj,‘dev‘)func()

拓展:

  import 模块 (反射实现):

  a = __import__("模块名")

  a = __import__(‘lib.test.com‘, fromlist=True)

python——面向对象相关

评论关闭