python 多態


多態
類具有繼承關系,並且子類類型可以向上轉型看做父類類型,如果我們從 Person 派生出 Student和Teacher ,並都寫了一個 whoAmI() 方法:

class Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender
    def whoAmI(self):
        return 'I am a Person, my name is %s' % self.name

class Student(Person):
    def __init__(self, name, gender, score):
        super(Student, self).__init__(name, gender)
        self.score = score
    def whoAmI(self):
        return 'I am a Student, my name is %s' % self.name

class Teacher(Person):
    def __init__(self, name, gender, course):
        super(Teacher, self).__init__(name, gender)
        self.course = course
    def whoAmI(self):
        return 'I am a Teacher, my name is %s' % self.name
在一個函數中,如果我們接收一個變量 x,則無論該 x 是 Person、Student還是 Teacher,都可以正確打印出結果:

def who_am_i(x):
    print x.whoAmI()

p = Person('Tim', 'Male')
s = Student('Bob', 'Male', 88)
t = Teacher('Alice', 'Female', 'English')

who_am_i(p)
who_am_i(s)
who_am_i(t)
運行結果:

I am a Person, my name is Tim
I am a Student, my name is Bob
I am a Teacher, my name is Alice
這種行為稱為多態。也就是說,方法調用將作用在 x 的實際類型上。s 是Student類型,它實際上擁有自己的 whoAmI()方法以及從 Person繼承的 whoAmI方法,但調用 s.whoAmI()總是先查找它自身的定義,如果沒有定義,則順着繼承鏈向上查找,直到在某個父類中找到為止。

由於Python是動態語言,所以,傳遞給函數 who_am_i(x)的參數 x 不一定是 Person 或 Person 的子類型。任何數據類型的實例都可以,只要它有一個whoAmI()的方法即可:

class Book(object):
    def whoAmI(self):
        return 'I am a book'
這是動態語言和靜態語言(例如Java)最大的差別之一。動態語言調用實例方法,不檢查類型,只要方法存在,參數正確,就可以調用。

任務
Python提供了open()函數來打開一個磁盤文件,並返回 File 對象。File對象有一個read()方法可以讀取文件內容:

例如,從文件讀取內容並解析為JSON結果:

import json
f = open('/path/to/file.json', 'r')
print json.load(f)
由於Python的動態特性,json.load()並不一定要從一個File對象讀取內容。任何對象,只要有read()方法,就稱為File-like Object,都可以傳給json.load()。

請嘗試編寫一個File-like Object,把一個字符串 r'["Tim", "Bob", "Alice"]'包裝成 File-like Object 並由 json.load() 解析。

?不會了怎么辦
只要為Students類加上 read()方法,就變成了一個File-like Object。

參考代碼:

import json

class Students(object):
    def read(self):
        return r'["Tim", "Bob", "Alice"]'

s = Students()

print json.load(s)

 

python的多態用一句話概括就是,有這種方法,並且傳入相應的參數就行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM