1. 程式人生 > >python 面向物件(三)

python 面向物件(三)

繼承:

#一般寫程式碼時,是一個類一個檔案,所以當類繼承時,需要呼叫模組#
#設父類、子類都在一個目錄下,父類為free.py,子類為fuze.py#



#第一種繼承#
#父類:#
class LexName():
    name = ''

    def __init__(self,name):
        self.name = name

    def Hello(self,a,__name):
        self.a = a
        self.__name = __name
        if a < 0:
            print('不能打負分')
        elif a > 100:
            print('不能超過100分')
        else:
            print(self.__name + '同學,分數為:' + str(self.a) + '分')
        return a,__name
#子類:#
import free
class Fox(free.LexName):
    pass

#第二種(較為常用):#
#子類:#
from free import LexName
class Fox(LexName):
    pass



#在子類中呼叫父類的建構函式變數:#
#第一種(這一種沒有意義,但是也可以呼叫):#
from free import LexName

class Fox(LexName):
    number = 0

    def __init__(self,number,name):
        self.number = number
        LexName.__init__(self,name) 

    def First(self):
        pass

fox1 = Fox(70,'知易行難')
print(fox1.number)
print(fox1.name)

#在子類中呼叫父類的建構函式變數:#
#第二種(常見的是這一種,利用super傳遞):#
from free import LexName

class Fox(LexName):
    number = 0

    def __init__(self,number,name):
        self.number = number
        super(Fox,self).__init__(name)

    def First(self):
        pass

fox1 = Fox(70,'知易行難')
print(fox1.number)
print(fox1.name)



#子類例項(非建構函式)也可以呼叫父類例項(非建構函式)#
#父類:#
class LexName():
    name = ''

    def __init__(self,name):
        self.name = name
    
    def Hello(self,a,name1):
        self.a = a
        self.name1 = name1
        if a < 0:
            print('不能打負分')
        elif a > 100:
            print('不能超過100分')
        else:
            print(self.name1 + '同學,分數為:' + str(self.a) + '分')
        return a,name1
#子類:#
from free import LexName

class Fox(LexName):
    number = 0

    def __init__(self,number,name):
        self.number = number
        super(Fox,self).__init__(name)

    def First(self,a,name1):
        super(Fox,self).Hello(a,name1)
        print('ninhao')

fox1 = Fox(70,'知易行難')
print(fox1.number)
print(fox1.name)
fox1.First(90,'知易行難')