繼承
繼承描述了基類的屬性如何“遺傳”給派生類。一個(gè)子類可以繼承它的基類的任何屬性,不管是數(shù)據(jù)屬性還是方法。
創(chuàng)建子類的語法看起來與普通(新式)類沒有區(qū)別,一個(gè)類名,后跟一個(gè)或多個(gè)需要從其中派生的父類:
代碼如下:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'optional class documentation string'
class_suite
實(shí)例
代碼如下:
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'
繼承與覆蓋
繼承
不同于Java,python的子類繼承父類后,會(huì)把父類的所有的方法,包括構(gòu)造器init()也繼承下來.
代碼如下:
class Parent():
def __init__(self):
print "init Parent class instance"
def func(self):
print "call parent func"
class Child(Parent):
def __init__(self):
print "init Child class instance"
child = Child()
child.func()
輸出
代碼如下:
init Child class instance
call parent func
super關(guān)鍵字
super 是用來解決多重繼承問題的,直接用類名調(diào)用父類方法在使用單繼承的時(shí)候沒問題,但是如果使用多繼承,會(huì)涉及到查找順序(MRO)、重復(fù)調(diào)用(鉆石繼承)等種種問題。語法如下
代碼如下:
super(type[, obj])
示例
代碼如下:
class C(B):
def method(self, arg):
super(C, self).method(arg)
注意
super繼承只能用于新式類,用于經(jīng)典類時(shí)就會(huì)報(bào)錯(cuò)。
新式類:必須有繼承的類,如果沒什么想繼承的,那就繼承object
經(jīng)典類:沒有父類,如果此時(shí)調(diào)用super就會(huì)出現(xiàn)錯(cuò)誤:『super() argument 1 must be type, not classobj』
實(shí)例
代碼如下:
class Parent(object):
def __init__(self):
self.phone = '123456'
self.address = 'abcd'
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
self.data = 100
def main():
child = Child()
print "phone is: ", child.phone
print "address is: ", child.address
新聞熱點(diǎn)
疑難解答
圖片精選