Python基础(六)其他
其他相关
一、isinstance(obj, cls)
检查是否obj是否是类 cls 的对象
class Foo(object): pass obj = Foo() isinstance(obj, Foo)
二、issubclass(sub, super)
检查sub类是否是 super 类的派生类
class Foo(object): pass class Bar(Foo): pass issubclass(Bar, Foo)
三、异常处理
1、异常基础
在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,一般情况下不会让用户看见大黄页!!!
try: pass except Exception,ex: pass
2、异常种类
python中的异常种类非常多,每个异常专门用于处理某一项异常!!!
常用异常
更多异常异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。
# 未捕获到异常,程序直接报错 s1 = 'hello' try: int(s1) except IndexError,e: print (e)
所以,写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:
s1 = 'hello' try: int(s1) except IndexError,e: print (e) except KeyError,e: print (e) except ValueError,e: print (e)
万能异常 在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即:
s1 = 'hello' try: int(s1) except Exception,e: print (e)
对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行。
s1 = 'hello' try: int(s1) except KeyError,e: print ('键错误') except IndexError,e: print ('索引错误') except Exception, e: print ('错误')
3、异常其他结构
try: # 主代码块 pass except KeyError,e: # 异常时,执行该块 pass else: # 主代码块执行完,执行该块 pass finally: # 无论异常与否,最终执行该块 pass
4、主动触发异常
try: raise Exception('错误了。。。') except Exception,e: print (e)
5、自定义异常
class smiledException(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.message try: raise smiledException('我的异常') except smiledException,e: print (e)
6、断言
|
1
2
3
4
5
|
# assert 条件assert 1 == 1assert 1 == 2 |
四、反射
python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
class Foo(object): def __init__(self): self.name = 'smiled' 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')
详细解析:
当我们要访问一个对象的成员时,应该是这样操作:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Foo(object): def __init__(self): self.name = 'alex' def func(self): return 'func'obj = Foo()# 访问字段obj.name# 执行方法obj.func() |
View Code答:有两种方式,如下:
方式一
方式二d、比较三种访问方式
- obj.name
- obj.__dict__['name']
- getattr(obj, 'name')
答:第一种和其他种比,...
第二种和第三种比,...
Web框架实例
结论:反射是通过字符串的形式操作对象相关的成员。一切事物都是对象!!!
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys def s1(): print ('s1') def s2(): print ('s2') this_module = sys.modules[__name__] hasattr(this_module, 's1') getattr(this_module, 's2')
类也是对象
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Foo(object): staticField = "old boy" def __init__(self): self.name = 'wupeiqi' def func(self): return 'func' @staticmethod def bar(): return 'bar'print getattr(Foo, 'staticField')print getattr(Foo, 'func')print getattr(Foo, 'bar') |
模块也是对象
home.py|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/usr/bin/env python# -*- coding:utf-8 -*-"""程序目录: home.py index.py当前文件: index.py"""import home as obj#obj.dev()func = getattr(obj, 'dev')func() |
设计模式
一、单例模式
单例,顾名思义单个实例。
面向对象场景:
如:创建对数据库操作的公共类
- 增
- 删
- 改
- 查
View Code
实例:结合上述场景实现Web应用程序
Web应用程序实例对于上述实例,每个请求到来,都需要在内存里创建一个实例,再通过该实例执行指定的方法。
那么问题来了...如果并发量大的话,内存里就会存在非常多功能上一模一样的对象。存在这些对象肯定会消耗内存,对于这些功能相同的对象可以在内存中仅创建一个,需要时都去调用。
那单例模式就是用来保证内存中仅存在一个实例!!!
通过面向对象的特性,构造出单例模式:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# ########### 单例类定义 ###########class Foo(object): __instance = None @staticmethod def singleton(): if Foo.__instance: return Foo.__instance else: Foo.__instance = Foo() return Foo.__instance# ########### 获取实例 ###########obj = Foo.singleton() |
对于Python单例模式,创建对象时不能再直接使用:obj = Foo(),而应该调用特殊的方法:obj = Foo.singleton() 。
Web应用实例-单例模式总结:单利模式存在的目的是保证当前内存中仅存在单个实例,避免内存浪费!!!

浙公网安备 33010602011771号