python基礎之調用父類的方法

方法一:

>>> class cat(object):#父類
	def eat(self):
		print("the cats love fishes")

>>> class BlackCat(cat):#子類
	def eat(self):
		cat.eat(self)#調用父類的方法
		print("the BlackCat love mouse too")		
>>> kity=BlackCat()
>>> kity.eat()
the cats love fishes
the BlackCat love mouse too

方法二:使用super()

>>> class cat(object):
	def eat(self):
		print("the cats love fishes")

		
>>> class BlackCat(cat):
	def eat(self):
		super().eat() #使用super調用父類方法
		print("the BlackCat love mouse too")		
>>> kity=BlackCat()
>>> kity.eat()
the cats love fishes
the BlackCat love mouse too

鑽石繼承:普通方法會遇到Base兩次初始化的問題,super()方法不會。如下圖

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