1. 程式人生 > >【Python】Python中基類函式的過載和基類函式的呼叫

【Python】Python中基類函式的過載和基類函式的呼叫

剛接觸Python語言的時間不長,對於這個語言的很多特性並不是很瞭解,有很多用法都是還不知道。今天想著寫一個Python面向物件程式設計時的繼承中的函式呼叫。分享出來,一起進步。

因為之前接觸過Java和C++,所有對於面向物件的思想也早已經很熟析的了。這裡也不再對面向物件是什麼進行贅述了。我們直接上程式碼吧!看看對於繼承和基類函式的呼叫在Python中是如何呼叫的~

首先,是基類檔案base.py

'''
Created on Dec 18, 2014

@author: raul
'''

class animal(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        print 'animal init'
        
    def say(self):
        print 'animal say'

然後,是子類檔案child.py
'''
Created on Dec 18, 2014

@author: raul
'''
from inheritance.base import animal

class cat(animal):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
#         animal.__init__()
        animal.__init__(self)
        print 'cat init'
        
    def say(self):
        animal.say(self)
        print 'cat say'


if __name__ == '__main__':
    c = cat()
    c.say()
    

執行後,就可以看到輸出,如下:
animal init
cat init
animal say
cat say

這就說明,我們的繼承和函式的呼叫都已經OK了