第八章 异常
8.1 捕捉异常
try:
x = input(“enter a number: “)
except ZeroDivisionError:
print “the second number can not be zero!”
上面的except子句可以有多个,可以捕捉多种类的异常。
8.2 全捕捉
try:
x = input(“enter a number: “)
except:
print “something wrong!”
8.3 没坏事发生时执行一段代码
try:
x = input(“enter a number: “)
except:
print “what is wrong!”
else:
print “that is no wrong things happen”
8.4 finally
finally:子句肯定被执行
8.5 异常和函数
- 产生的异常会随着函数,函数调用,主程序传播,最终会导致栈跟踪。
- 如果不想让异常出现之前被输出,可以用”+”号
如:
try:
print “Occupation: ” + person‘occupation’
第九章 魔方方法,属性和迭代器
9.1 构造方法
- 形式: init()
继承时,构造函数会重写
class Bird: def __init()__(self): self.hungry = True def eat(self): if self.hungry: print 'Aaa...' self.hungry = Fase else: print 'Not hungry' class SongBird(Bird): def __init__(self): self.sound = 'Squawk' def sing(self): print self.sound
当用
S = SongBird()
调用eat()
会出错,因为SongBird
重写了构造函数,而在它的构造函数里没有定义hungry
这个变量。
解决方法:
(1)调用未绑定的超类构造函数方法:class Bird: def __init()__(self): self.hungry = True def eat(self): if self.hungry: print 'Aaa...' self.hungry = Fase else: print 'Not hungry' class SongBird(Bird): def __init__(self): ``` Bird.__init__(self) ``` self.sound = 'Squawk' def sing(self): print self.sound
(2)使用super函数:
class Bird: def __init()__(self): self.hungry = True def eat(self): if self.hungry: print 'Aaa...' self.hungry = Fase else: print 'Not hungry' class SongBird(Bird): def __init__(self): ``` super(SongBird,self).__init__() ``` self.sound = 'Squawk' def sing(self): print self.sound
比较这两种方法:
super
更优,更智能,即使类有多个超类,只需要一次super
,在两个超类继承同一个超类,super
会自动处理。
8.3 成员访问
函数 | 作用 |
---|---|
len | 返回集合中所含项目的数量 |
getitem | 返回与键所对应的值 |
setitem | 按一定方式存储与key相关的value,该值随后可以用getitem访问 |
delitem | 删除对象时,同时删除和键相关的键 |
8.4 property函数(代替set,get方法)
#能将get和set方法隐藏起来,使用时不用考虑是否用get/set实现,直接当属性一样使用
__metaclass__= type
class Rectangle:
self.width = 0
self.height = 0
def setSize(self,size):
self.width,self.height = size
def getSize(self,size):
return self.width,self.height
size = property(getSize,setSize)
r = Rectangle()
r.width = 5
r.height = 10
r.size:(5,10)
r.size = 50,19
r.width:50
8.5 静态方法和类成员方法
__metaclass__=type
class MyClass:
def smeth():
print 'This is a static method'
smeth = staticmethod(smeth)
def cmeth(cls):
print 'This is a class method of',cls
cmeth=classmethod(cmeth)
加上装饰器后不用实例化:
__metaclass__=type
@staticmethod
class MyClass:
def smeth():
print 'This is a static method'
@classmethod
def cmeth(cls):
print 'This is a class method of',cls
8.6 迭代器
要调用next()
方法时,迭代器才返回它的下一个值,要有next()
和iter()
函数:
class Fibs:
def __init__(self):
self.a = 0
self.b = 0
def next(self):
self.a,self.b = self.b,self.a+self.b
return self.a
def __iter__(self):
return self
for f in Fibs:
print f
结果会一个个打印出b值。
8.7生成器
#递归生成器,nested=[[1,2],3]
def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
print 'element:',element
yield element
except TypeError:
print "nested:",nested
yield nested
#运行
flatten(nested)
结果:
nested:1
element:1
element:1
nested:2
element:2
element:2
nested:3
element:3
结果解析:运行yield
语句时,函数停止,当时递归时就会返回上一层继续执行上一层的断点。
生成器解决八皇后问题:
#判断冲突函数
def conflict(state,nextX):
nextY = len(state)
for i in range(nextY):
if abs(nextX-state[i]) in (0,nextY-i):#当水平距离等于垂直距离或和前一个皇后水平距离为0时冲突
return True
return False
#解决函数,pos每取一个值计算一种可能
def queens(num,state=()):
for pos in range(num):
if not conflict(state,pos):
if len(state)==num-1:#当最后一个递归时返回,返回到最后一层时再次调用
yield (pos,)
else:
for result in queens(num,state+(pos,)):#
yield (pos,)+result
运行:list(queens(4))
结果:[(1, 3, 0, 2), (2, 0, 3, 1)]
运行:len(list(queens(8)))
结果:92