python繼承和重寫init方法

常城發表於2013-06-26

程式碼如下:

#! /usr/bin/env python
#coding=utf-8

class Dad(object):
    def __init__(self, surname ):
        self.surname = surname
    
class Son_1(Dad):
    def __init__(self, surname, name ):
        Dad.__init__(self, surname)
        self.name = name

class Son_2(Dad):
    def __init__(self, surname):
        Dad.__init__(self, surname)
        self.name = 'Si'

if __name__ == '__main__': 
    son_1 = Son_1('Li', 'Goudan')
    print son_1.surname, son_1.name
    son_2 = Son_2('Li')
    print son_2.surname, son_2.name
    


 

結果:

>>>
Li Goudan
Li Si
>>>

 

相關文章