作用:一個(gè)接口母截,多種實(shí)現(xiàn)
目的:接口的重(chong)用
剛一開(kāi)始可能會(huì)不理解惜互,什么接口,怎么實(shí)現(xiàn)率挣,下面我門就通過(guò)一個(gè)例子來(lái)看一下多態(tài)是怎么實(shí)現(xiàn)的
class People(object):
def __init__(self, name):
self.name = name
class Man(People):
def walk(self):
print('%s is walking' % self.name)
class Woman(People):
def walk(self):
print('%s is walking' % self.name)
def people_walk(obj):
obj.walk()
man1 = Man('xiaoming')
man1.walk()
man2 = Woman('ruhua')
man2.walk()
簡(jiǎn)單的三個(gè)類刻伊,兩個(gè)子類都繼承了父類People,父類中有構(gòu)造函數(shù)初始化name變量椒功,兩個(gè)子類中都有一個(gè)walk函數(shù)捶箱,實(shí)例化了兩個(gè)對(duì)象man1和man2,分別調(diào)用了walk函數(shù)动漾,實(shí)現(xiàn)了輸出這兩句話
但是我們能不能寫一個(gè)函數(shù)丁屎,當(dāng)作一個(gè)接口,傳入對(duì)象就可以執(zhí)行walk函數(shù)旱眯,而不是用這個(gè)對(duì)象來(lái)調(diào)用walk函數(shù)呢晨川?
寫了一個(gè)people_walk的函數(shù),實(shí)現(xiàn)了這個(gè)接口删豺,但是是寫在類外共虑,有沒(méi)有可以優(yōu)化的地方呢?
class People(object):
def __init__(self, name):
self.name = name
@staticmethod
def people_walk(obj):
obj.walk()
class Man(People):
def walk(self):
print('%s is walking' % self.name)
class Woman(People):
def walk(self):
print('%s is walking' % self.name)
# def people_walk(obj):
# obj.walk()
man1 = Man('xiaoming')
# man1.walk()
man2 = Woman('ruhua')
# man2.walk()
People.people_walk(man1)
People.people_walk(man2)
我們把people_walk函數(shù)移到了父類中呀页,并且用了一個(gè)類似裝飾器的東西@staticmethod
(具體請(qǐng)戳靜態(tài)方法妈拌,類方法,屬性方法)
看蓬蝶,walk函數(shù)有了一個(gè)共同的接口:
People.people_walk()
想讓誰(shuí)走就把誰(shuí)傳進(jìn)去就行了
這樣尘分,我們就實(shí)現(xiàn)了一個(gè)接口,多種實(shí)現(xiàn)
轉(zhuǎn)載請(qǐng)注明出處
python自學(xué)技術(shù)互助扣扣群:670402334