python(一):構造方法 /類的初始化

python(一):構造方法 /類的初始化

init

當類中的一個對象被創建時,會立即調用構造方法。
構造方法 init的使用:

class FooBar:
    def __init__(self):
        self.somevar = 42
f = FooBar()
print f.somevar

(這裏注意f = FooBar(),要帶括號)
輸出結果:

42

  • 帶參數構造
class FooBar:
    def __init__(self,value=42):
        self.somevar = value
f = FooBar("this is a constructor argument")
print f.somevar

輸出結果:

this is a constructor argument

重寫構造方法

子類中如果重寫了構造方法, 那麼就自動覆蓋掉了父類構造方法了,那麼如果只是想在子類構造方法中增加一些內容,如何做到只是增加內容而不覆蓋父類中原有的內容呢?有兩種方法:

  1. 調用未綁定的超類構造方法
    首先看一個例子:
class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print "Aaaah"
            self.hungry = False
        else:
            print "No,thanks"

定義了一個父類 Bird。下面定義一個子類:

class SingBird:
    def __init__(self):
        Bird.__init__(self)
        self.sound = "squawk"
    def sing(self):
        print self.sound

這裏使用了

Bird.init(self)
這樣就可以在父類的基礎上增加內容了。
2. 使用super函數

class SingBird:
    def __init__(self):
        super(SingBird,self).__init__()
        self.sound = "squawk"
    def sing(self):
        print self.sound

使用

super(SingBird,self).init()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章