本文實例講述了python創建子類的方法。分享給大家供大家參考,具體如下:
如果你的類沒有從任何祖先類派生,可以使用object作為父類的名字。經典類的聲明唯一不同之處在于其沒有從祖先類派生---此時,沒有圓括號:
# !/usr/bin/env python# -*- coding: utf-8 -*-class ClassicClassWithoutSuperclasses: def fun1(self): print 'aaaaaaa'a=ClassicClassWithoutSuperclasses()print aprint type(a)print a.fun1()
C:/Python27/python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
<__main__.ClassicClassWithoutSuperclasses instance at 0x0047BDF0>
<type 'instance'>
aaaaaaa
None
至此,我們已經看到了一些類和子類的例子,下面還有一個簡單的例子:
class Parent(object): # define parent class 定義父類 def parentMethod(self): print 'calling parent method
# !/usr/bin/env python# -*- coding: utf-8 -*-class Parent(object): # define parent class 定義父類 def parentMethod(self): print 'calling parent method'class Child(Parent): # define child class 定義子類 def childMethod(self): print 'calling child method'a=Parent() # instance of parent 父類的實例print a.parentMethod()
C:/Python27/python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
calling parent method
None
>>> c = Child() # instance of child 子類的實例>>> c.childMethod() # child calls its method 子類調用它的方法calling child method>>> c.parentMethod() # calls parent's method 調用父類的方法calling parent method
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答