异常 反射
一、异常处理:
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 更多异常 更多异常
更多异常
1 try:
2 intput = raw_input()
3 data = int(intput)
4 except Exception,e: #e是Exception类的一个对象,调用__str__方法
5 print"请输入数字"
#输出sb,输出A类的__str__方法 class A:
def __str__(self):
return 'sb'
obj = A()
print obj #自定义错误异常 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('error') #当有值时,输出值,否则输出alex erroer
except Exception,e:
print e 自定义异常
自定义异常
二、反射:
helpper.py #模块
-----------------------------------------------
def dev():
return "home dev"
def index():
return "home index" index.py #模块
-----------------------------------------------
import helpper url = raw_input('url:') #输入helpper/dev if url == "helpper/dev":
ret = helpper.dev()
print ret
elif url == "helpper/index":
ret = helpper.index()
print ret Example
Example
helpper.py #模块
-----------------------------------------------
def dev():
return "home dev"
def index():
return "home index" index.py #模块
-----------------------------------------------
import helpper url = raw_input('url:') #输入helpper/dev
controller,action = url.split('/')
func = getattr(helpper,action)
ret = func()
print ret Example 进阶
Example 进阶
helpper.py #模块
--------------------------------------------
def dev():
return "home dev"
def index():
return "home index" index.py #模块
---------------------------------------------
controller,action = raw_input("url:").split('/')
model = __import__(controller) func = getattr(model,action)
ret = func()
print ret __import__和反射 getattr
__import__和反射 getattr
二、反射(2):
import sys class WebServer(object):
def __init__(self,host,port):
self.host = host
self.port = port
def start(self):
print("Server is starting...")
def stop(self):
print("Server is stopping...")
def restart(self):
self.stop()
self.start()
if __name__ == "__main__":
obj = WebServer('localhost','')
if sys.argv[1] == "start":
obj.start() example
example
import sys class WebServer(object):
def __init__(self,host,port):
self.host = host
self.port = port
def start(self):
print("Server is starting...")
def stop(self):
print("Server is stopping...")
def restart(self):
self.stop()
self.start()
if __name__ == "__main__":
obj = WebServer('localhost','')
cmd_list = {
'start':obj.start,
'stop':obj.stop
}
if sys.argv[1] in cmd_list:
cmd_list[sys.argv[1]]() example 字典形式
example 字典形式
import sys class WebServer(object):
def __init__(self,host,port):
self.host = host
self.port = port
def start(self):
print("Server is starting...")
def stop(self):
print("Server is stopping...")
def restart(self):
self.stop()
self.start()
if __name__ == "__main__":
obj = WebServer('localhost','')
if hasattr(obj,sys.argv[1]):
func = getattr(obj,sys.argv[1]) #获取obj.start 的内存地址
func() example 进阶hasattr getattr
example 进阶hasattr getattr
import sys class WebServer(object):
def __init__(self,host,port):
self.host = host
self.port = port
def start(self):
print("Server is starting...")
def stop(self):
print("Server is stopping...")
def restart(self):
self.stop()
self.start() def test_run(name):
print("running..",name) if __name__ == "__main__":
obj = WebServer('localhost','')
if hasattr(obj,sys.argv[1]):
func = getattr(obj,sys.argv[1]) #获取obj.start 的内存地址
func()
setattr(obj,"run",test_run)
obj.run('xxx') ---------------------------------------------------------------------- #/usr/bin/env python
# -*- coding:utf-8 -*- import sys class WebServer(object):
def __init__(self,host,port):
self.host = host
self.port = port
def start(self):
print("Server is starting...")
def stop(self):
print("Server is stopping...")
def restart(self):
self.stop()
self.start() def test_run(self,name):
print("running..",name,self.host) if __name__ == "__main__":
obj = WebServer('localhost','')
if hasattr(obj,sys.argv[1]):
func = getattr(obj,sys.argv[1]) #获取obj.start 的内存地址
func()
setattr(obj,"run",test_run)
obj.run(obj,'xxx') setattr
setattr
三、设计模式:
class SqlHelper: __static_instance = None def __init__(self):
self.hostname = '0.0.0.0'
self.port = 3306
self.user = 'root'
self.passd = '' @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 add_user():
obj = SqlHelper.instance()
obj.fetch() def del_user():
obj = SqlHelper.instance()
obj.remove() print id(SqlHelper.instance())
print id(SqlHelper.instance()) 单例模式一
单例模式一