Python中呼叫父類的同名方法

2021-06-17 21:35:23 字數 792 閱讀 2011

物件導向設計時,無可避免的會涉及到父類和子類的關係

封裝、整合、多型,大家都能娓娓道來

道理是一樣的,針對不同的語言,物件導向開發也會遇到不同情況需要解決

今天學習下python中如何呼叫父類同名方法

ps: 如果不呼叫的話,子類同名方法對父類方法是直接覆蓋的

class fooparent:

def bar(self, message):

print(message)

class foochild(fooparent):

def bar(self, message):

fooparent.bar(self, message)

>>> foochild().bar("hello, world.")

hello, world.

缺點:

class fooparent:

def bar(self, message):

print(message)

class foochild(fooparent):

def bar(self, message):

super(foochild, self).bar(message)

>>> foochild().bar("hello, world.")

hello, world.

優點:

參考:如何在python中呼叫父類的同名方法

posted by lynnliu

jun 8th, 2013 python

在Python多繼承中呼叫父類的同名方法

coding utf 8 類定義 class people object 定義基本屬性 name age 0 定義私有屬性 weight 0 定義構造方法 def init self,n,a,w self.name n self.age a self.weight w 定義方法 defspeak s...

Python 當父類擁有同名的方法

繼承作為物件導向的三大特性之一,為我們的程式設計帶來極大的便利,更好地掌握繼承能夠讓我們寫出更加優美簡潔的 本篇部落格意在讓讀者了解當父類擁有同名方法時,子類繼承方法的規則。首先觀察以下兩個示例 class a def method1 self print a class b def method1...

php不呼叫父類構造 php呼叫父類構造方法是什麼

php呼叫父類構造方法 首先父類先建構函式,為 public function construct 然後使用 parent construct 呼叫父類建構函式即可。php呼叫父類構造方法 一 使用函式 parent construct 呼叫父類建構函式 如下 class myclass 父類 pu...