一年前就打算學Python了,折騰來折騰去也一直沒有用熟練,主要是類那一塊不熟,昨天用Python寫了幾個網絡編程的示例,感覺一下子邁進了很多。這幾天把學習Python的筆記整理一下,內容盡量簡潔。
下面這個例子演示類的基本使用:
# coding:utf-8class Test(): s = '這是一個靜態變量' def __init__(self): PRint '這里是構造函數' self.a = 1 self.b = 12 def __del__(self): print '這里是析構函數' def foo(self): print '普通成員函數' @staticmethod def bar(): print '類的靜態函數'if __name__ == '__main__': t = Test() t.foo() Test.bar() print t.__class__ print Test.__bases__ print Test.s
很多書上很啰嗦的介紹Python的類,但是很多Python學習者本身已經具備了C++或者java的基礎,所以我直接嘗試寫了這個一個demo。
在Python中,構造函數使用了__init__,析構函數則使用了__del__。
在C++中,類的成員變量和函數都是編譯之前就確定了,而Python可以再運行期確定。
上例中的s相當于靜態變量,整個類共同擁有。
__init__函數中的self.a屬于普通成員變量。如果你在某一個函數中使用了
self.c = 'foo'
但是這里注意,只有運行這一行之后,對象的數據成員才添加了c。所以,Python的成員變量是可以在運行過程中增減的。
再看第二個示例,關于繼承和組合的:
# coding:utf-8class Base(): def __init__(self, a, b): print 'Base construct.' self.a = a; self.b = b; self.t = Other() def __del__(self): print 'Base destroy.' def foo(self): print 'a = %s b = %s' % (self.a, self.b)class Other(): def __init__(self): print 'Other construct.' def __del__(self): print 'Other destroy.'class Derived(Base): def __init__(self, a, b): Base.__init__(self, a, b) print 'Derived construct.' def __del__(self): Base.__del__(self) print 'Derived destroy.'if __name__ == '__main__': d = Derived("foo", "bar") d.foo() print d.__class__ print d.__class__.__bases__ print Derived.__bases__
Base是基類,Derived從Base中繼承,同時Other類的一個對象是Derived的一個數據成員。
在本例中,注意,Derived的構造函數中,必須手工調用Base的構造函數,析構函數也是相同的用法。
最后一個例子,關于基類和派生類的函數覆蓋問題:
# coding:utf-8class Foo(): def test(self): print 'test in Base.'class Bar(Foo): def test(self): print 'test in Derived.'if __name__ == '__main__': b = Bar() b.test()
我們運行程序,打印的是:
test in Derived.
這里需要注意,與C++不同,這里的Bar中的test函數,即使改變了參數也無所謂,總之,只要函數與基類中的函數重名,那就構成了覆蓋。
如果在Bar的test函數中想調用基類的版本,可以使用:
Foo.test(self)
完整的代碼如下:
# coding:utf-8class Foo(): def test(self): print 'test in Base.'class Bar(Foo): def test(self): Foo.test(self) print 'test in Derived.'if __name__ == '__main__': b = Bar() b.test()
完。
新聞熱點
疑難解答