Python基類函數的重載與調用學習教程

來源:互聯網
上載者:User

剛接觸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了

此例子比較簡單,不過基本上也講明白了Python基類函數的重載與調用,希望學習的同學可以舉一反三。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.