要了解什麼是多态,我們首先要對資料類型再作一點說明,當我們定義一個class的時候,
我們實際上就定義了一種資料類型,我們定義的資料類型和Python自帶的資料類型,比如str,list,dict沒什麼兩樣:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2)
from mycompany.web.Student import *
c = Student('a',88)
print c.name
print isinstance(c, Student)
print c.print_score()
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
a
True
a: 86
None
a = list() # a是list類型
b = Animal() # b是Animal類型
c = Dog() # c是Dog類型
判斷一個變量是否是某個類型可以用isinstance()判斷:
>>> isinstance(a, list)
True
>>> isinstance(b, Animal)
True
>>> isinstance(c, Dog)
Tru
from mycompany.web.Dog import *
c = Dog()
c.run()
print isinstance(c, Dog)
print isinstance(c, Animal)
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
yy
Animal is running...
True
True
from mycompany.web.Dog import *
b = Animal()
print b.run()
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
yy
Animal isxx running...
None
from mycompany.web.Dog import *
def run_twice(animal):
animal.run()
print '----------------'
run_twice(Animal())
run_twice(Dog())
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
----------------
Animal isxx running...
Dog isxx running...
Process finished with exit code 0
看上去沒啥意思,但是仔細想想,現在,如果我們再定義一個Tortoise類型,也從Animal派生:
class Tortoise(Animal):
def run(self):
print 'Tortoise is running slowly...'
from mycompany.web.Tortoise import *
def run_twice(animal):
animal.run()
print '----------------'
run_twice(Animal())
run_twice(Tortoise())
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
----------------
Animal isxx running...
Tortoise is running slowly...
Process finished with exit code 0
你會發現,新增一個Animal的子類,不必對run_twice()做任何修改,
實際上,任何依賴Animal 作為的函數的函數或者方法都可以不加修改地正常運作,原因在于多态
from mycompany.web.Tortoise import *
def run_twice(animal):
animal.run()
print '----------------'
run_twice(Animal())
run_twice(Tortoise())
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
xxxx
----------------
Animal isxx running...
Animal isxx running...