文章標題

第八章 異常

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 異常和函數

  1. 產生的異常會隨着函數,函數調用,主程序傳播,最終會導致棧跟蹤。
  2. 如果不想讓異常出現之前被輸出,可以用”+”號
    如:
    try:
    print “Occupation: ” + person‘occupation’

第九章 魔方方法,屬性和迭代器

9.1 構造方法

  1. 形式: init()
  2. 繼承時,構造函數會重寫

    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

發佈了36 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章