面向对象及相关

一、isinstance(obj, cls)

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

class Foo(object):
    pass
 
obj = Foo()
 
isinstance(obj, Foo)

二、issubclass(sub, super)

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

class Bar():
    pass
class Foo(Bar):
    pass

obj = Foo()
ret = isinstance(obj,Foo)
ret1 = issubclass(Foo,Bar)
ret3 = isinstance(obj,Bar)
print(ret) #True
print(ret1)#True
print(ret3) #True

三、异常处理

1、异常基础

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

try:
    pass
except Exception,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没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的
常用异常
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
更多异常
实例:IndexError

 

dic = {'k1':'v1'}
try:
    dic['k20']
except KeyError, e:
    print e
实例:KeyError
s1 = 'hello'
try:
    int(s1)
except ValueError, e:
    print e
实例:ValueError

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

# 未捕获到异常,程序直接报错
 
s1 = 'hello'
try:
    int(s1)
except IndexError,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)
except TypeError as e:
    print(e)
#输出
invalid literal for int() with base 10: 'hello'

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

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)
#输出
invalid literal for int() with base 10: 'hello'

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

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

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

 3、异常其他结构

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

 4、主动触发异常

try:
    raise Exception('错误。。。')
except Exception as e:
    print(e)
#输出
错误。。。

 5、自定义异常

class JasonExceiption(Exception):
    def __init__(self,msg):
        self.message = msg
    def __str__(self):
        return self.message
try:
    raise JasonExceiption('Jason Exception')
except JasonExceiption as e:
    print(e)
#输出
Jason Exception

 6、断言

assert语句,如果没记错,这个东西在C或者C++里面也有的。属于短小的断言。下面的是来自python help document的说明:

Assert statements are a convenient way to insert debugging assertions into a program:

assert语句是一种插入调试断点到程序的一种便捷的方式

assert语句的使用格式

assert expression

 这个语句是等价于下面的个句式:

if __debug__:
    if not expression: raise AssertionError

 assert也可以用于多个表达式的断言

assert expression1, expression2

 我自己写的一个关于质数判定的assert使用示例

def isPrime(n):
    """This function return a number is a prime or not"""
    assert n >= 2
    from math import sqrt
    for i in range(2, int(sqrt(n))+1):
        if n % i == 0:
            return False
    return True
isPrime(0)
##输出

  assert n >= 2
  AssertionError

 

四.python的super用法

原文地址: http://www.cnblogs.com/herbert/archive/2011/09/29/2195219.html

super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。总之前人留下的经验就是:保持一致性。要不全部用类名调用父类,要不就全部用 super,不要一半一半。

普通继承

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print('Parent')

    def bar(self,message):
        print(message, 'from Parent')

class FooChild(FooParent):
    def __init__(self):
        FooParent.__init__(self)
        print('Child')

    def bar(self,message):
        FooParent.bar(self,message)
        print('Child bar function.')
        print(self.parent)

if __name__=='__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')
#输出

Parent
Child
HelloWorld from Parent
Child bar function.
I'm the parent.

 super继承

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print('Parent')

    def bar(self,message):
        print(message,'from Parent')

class FooChild(FooParent):
    def __init__(self):
        super(FooChild,self).__init__()
        print('Child')

    def bar(self,message):
        super(FooChild, self).bar(message)
        print('Child bar fuction')
        print(self.parent)

if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')
#输出

Parent
Child
HelloWorld from Parent
Child bar function.
I'm the parent.

 从运行结果上看,普通继承和super继承是一样的。但是其实它们的内部运行机制不一样,这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。
注意:super继承只能用于新式类,用于经典类时就会报错。
新式类:必须有继承的类,如果没什么想继承的,那就继承object
经典类:没有父类,如果此时调用super就会出现错误:『super() argument 1 must be type, not classobj』

更详细的参考

http://blog.csdn.net/johnsonguo/article/details/585193

总结
  1. super并不是一个函数,是一个类名,形如super(B, self)事实上调用了super类的初始化函数,
       产生了一个super对象;
  2. super类的初始化函数并没有做什么特殊的操作,只是简单记录了类类型和具体实例;
  3. super(B, self).func的调用并不是用于调用当前类的父类的func函数;
  4. Python的多继承类是通过mro的方式来保证各个父类的函数被逐一调用,而且保证每个父类函数
       只调用一次(如果每个类都使用super);
  5. 混用super类和非绑定的函数是一个危险行为,这可能导致应该调用的父类函数没有调用或者一
       个父类函数被调用多次。

 

五.有序字典

class MyDict(dict):
    def __init__(self):
        self.li = []
        super(MyDict,self).__init__()
    def __setitem__(self, key, value):
        self.li.append(key)
        super(MyDict,self).__setitem__(key,value)
    def __str__(self):
        temp_list = []
        for key in self.li:
            value = self.get(key)
            temp_list.append("'%s':%s" %(key,value))
        temp_str = "{" + ",".join(temp_list) + "}"
        return temp_str

obj = MyDict()
obj['k1']  = 123
obj['k2'] = 456
print(obj)
View Code

 

六、设计模式之单例模式

模式特点:保证类仅有一个实例,并提供一个访问它的全局访问点。

说明:     为了实现单例模式费了不少工夫,后来查到一篇博文对此有很详细的介绍,而且实现方式也很丰富,通过对代码的学习可以了解更多Python的用法。以下的代码出自GhostFromHeaven的专栏,地址:http://blog.csdn.net/ghostfromheaven/article/details/7671853。不过正如其作者在Python单例模式终极版所说:

方法一:

class Foo:
    instance = None
    def __init__(self,name):
        self.name = name
    @classmethod
    def get_instance(cls):
        #cls类名
        if cls.instance:
            return cls.instance
        else:
            obj = cls('alex')
            cls.instance = obj
            return obj
    def __str__(self):
        return self.name


obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)
obj = Foo('jason')
print(obj)

 方法二:

  1. #方法1,实现__new__方法  
  2. #并在将一个类的实例绑定到类变量_instance上,  
  3. #如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回  
  4. #如果cls._instance不为None,直接返回cls._instance
class Singleton(object):  
    def __new__(cls, *args, **kw):  
        if not hasattr(cls, '_instance'):  
            orig = super(Singleton, cls)  
            cls._instance = orig.__new__(cls, *args, **kw)  
        return cls._instance  
  
class MyClass(Singleton):  
    a = 1  
  
one = MyClass()  
two = MyClass() 
two.a = 3
print(one) #<__main__.MyClass object at 0x10238d048>
print(two) #<__main__.MyClass object at 0x10238d048>
print(one.a) #3
print(two.a) #3

 参考(goF设计模式):

《大话设计模式》Python版代码实现 http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

Java实现 http://www.runoob.com/design-pattern/design-pattern-tutorial.html

posted on 2016-06-29 14:31  Jason_wang_2016  阅读(250)  评论(0编辑  收藏  举报

导航