Python之路【第五篇】:面向对象及相关
面向对象基础
基础内容介绍详见一下两篇博文:
- 面向对象初级篇
- 面向对象进阶篇
其他相关
一、isinstance(obj, cls)
检查是否obj是否是类 cls 的对象
1 2 3 4 5 6 | class Foo(object): passobj = Foo()isinstance(obj, Foo) |
二、issubclass(sub, super)
检查sub类是否是 super 类的派生类
1 2 3 4 5 6 7 | class Foo(object): passclass Bar(Foo): passissubclass(Bar, Foo) |
三、异常处理
1、异常基础
在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!!
1 2 3 4 | try: passexcept Exception,ex: pass |
需求:将用户输入的两个数字相加
View Code2、异常种类
python中的异常种类非常多,每个异常专门用于处理某一项异常!!!
常用异常
更多异常
实例:IndexError
实例:KeyError
实例:ValueError对于上述实例,异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。
1 2 3 4 5 6 7 | # 未捕获到异常,程序直接报错s1 = 'hello'try: int(s1)except IndexError,e: print e |
所以,写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:
1 2 3 4 5 6 7 8 9 | s1 = 'hello'try: int(s1)except IndexError,e: print eexcept KeyError,e: print eexcept ValueError,e: print e |
万能异常 在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即:
1 2 3 4 5 | s1 = 'hello'try: int(s1)except Exception,e: print e |
接下来你可能要问了,既然有这个万能异常,其他异常是不是就可以忽略了!
答:当然不是,对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行。
1 2 3 4 5 6 7 8 9 | s1 = 'hello'try: int(s1)except KeyError,e: print '键错误'except IndexError,e: print '索引错误'except Exception, e: print '错误' |
3、异常其他结构
1 2 3 4 5 6 7 8 9 10 11 12 | try: # 主代码块 passexcept KeyError,e: # 异常时,执行该块 passelse: # 主代码块执行完,执行该块 passfinally: # 无论异常与否,最终执行该块 pass |
4、主动触发异常
1 2 3 4 | try: raise Exception('错误了。。。')except Exception,e: print e |
5、自定义异常
1 2 3 4 5 6 7 8 9 10 11 12 | class WupeiqiException(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.messagetry: raise WupeiqiException('我的异常')except WupeiqiException,e: print e |
6、断言
1 2 3 4 5 | # assert 条件assert 1 == 1assert 1 == 2 |
四、反射
python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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”View Code
答:有两种方式,如下:
方式一
方式二
d、比较三种访问方式
- obj.name
- obj.__dict__['name']
- getattr(obj, 'name')
答:第一种和其他种比,...
第二种和第三种比,...Web框架实例
结论:反射是通过字符串的形式操作对象相关的成员。一切事物都是对象!!!
反射当前模块成员类也是对象
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.py1 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() |
设计模式
一、单例模式
单例,顾名思义单个实例。
学习单例之前,首先来回顾下面向对象的内容:
python的面向对象由两个非常重要的两个“东西”组成:类、实例
面向对象场景一:
如:创建三个游戏人物,分别是:
- 苍井井,女,18,初始战斗力1000
- 东尼木木,男,20,初始战斗力1800
- 波多多,女,19,初始战斗力2500
View Code
面向对象场景二:
如:创建对数据库操作的公共类
- 增
- 删
- 改
- 查
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() 。

#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server# ########### 单例类定义 ###########
class DbHelper(object):__instance = Nonedef __init__(self):self.hostname = '1.1.1.1'self.port = 3306self.password = 'pwd'self.username = 'root'@staticmethoddef singleton():if DbHelper.__instance:return DbHelper.__instanceelse:DbHelper.__instance = DbHelper()return DbHelper.__instancedef fetch(self):# 连接数据库# 拼接sql语句# 操作passdef create(self):# 连接数据库# 拼接sql语句# 操作passdef remove(self):# 连接数据库# 拼接sql语句# 操作passdef modify(self):# 连接数据库# 拼接sql语句# 操作passclass Handler(object):def index(self):obj = DbHelper.singleton()print id(single)obj.create()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 retelse:return '404 not found'if __name__ == '__main__':httpd = make_server('', 8001, RunServer)print "Serving HTTP on port 8001..."httpd.serve_forever()总结:单利模式存在的目的是保证当前内存中仅存在单个实例,避免内存浪费!!!









