接下來將訂一個父類別student
來處理每一個學生應該要有的特性,以及一個子類別Person
來加註學生的專業技能,而在這裡先做幾項說明:
class subclass_name(superclass_name):
super().__init__
會去呼叫父類別的initializer__init__
class student:
def __init__(self,name=None,gender=None,dep=None,ID=None):
self.name=name
self.gender=gender
self.dep=dep
self.ID=ID
class Person(student):
def __init__(self, name, gender, dep, ID, pro_qua):
super().__init__(name, gender, dep, ID)
self.pro_qua=pro_qua
def Profess(self):
General_Programming={'C','C++','C#','JAVA'}
Statics_Programming={'Python','R'}
Engineering_Programming={'Matlab','Fortran'}
if self.pro_qua in General_Programming:
return'General_Programming'
elif self.pro_qua in Statics_Programming:
return'Statics_Programming'
elif self.pro_qua in Engineering_Programming:
return 'Engineering_Programming'
else:
return 'Offices'
if __name__=='__main__':
A=Person('Eason','Male','Civil Engineering','9487943','Python')
print('Name:{} Department:{} ID:{}'.format(A.name,A.dep,A.ID))
print('Skill:{} ({})'.format(A.Profess(),A.pro_qua))
#output:
#Name:Eason Department:Civil Engineering ID:9487943
#Skill:Statics_Programming (Python)
大家可以進一步想一想怎麼做到多重繼承呢?
再多重繼承中,這時候不使用super().__init__
會去呼叫父類別,反而直接呼叫父類別的名稱,即supername.__init__(self, var1, var2, ...)
,可以決定自己的子類別中想要利用哪些變數就好,但原則上父類別中不用的變數會習慣放在最後變數的最後。
from functools import reduce
class student:
def __init__(self,name='Jack',gender='F',dep="IT",ID='9453',pro='Python'):
self.name=name
self.gender=gender
self.dep=dep
self.ID=ID
self.pro=pro
@property
def gender(self):
return self._gender
@gender.setter
def gender(self,gender):
if gender=='F':
self._gender='Female'
elif gender=='M':
self._gender='Male'
else:
raise TypeError('gender need F/M.')
return
class final_grade:
def __init__(self,we=[1,2,3],score=[1,2,3]):
self.we=we
self.score=score
def calculate(self):
weights=self.we
scores=self.score
ra=reduce(lambda a,b:a+b,map(lambda x,y:x*y,scores,weights))
return ra
class Person(student,final_grade):
def __init__(self, name, gender, dep, ID, we,score,bonus=0):
student.__init__(self, name, gender, dep, ID)
final_grade.__init__(self, we,score)
self.bonus=bonus
def total(self):
tot=self.bonus+self.calculate()
return tot
def rank(self):
total1=self.total()
if total1>=90: return 'A+'
elif total1>=80 and total1<90: return 'A'
elif total1>=70 and total1<80: return 'B'
elif total1>=60 and total1<70: return 'C'
else: return 'F'
# Main Function :
w=[0.25,0.35,0.4]
sc=[80,60,88]
A=Person('Eason','M','Civil Engineering','9487943',w,sc,2)
print('Name:{} Gender:{} Department:{} ID:{}'.format(A.name,A.gender,A.dep,A.ID))
print('Rank:{} (Initial Score:{})'.format(A.rank(),A.total()))
#output:
#Name:Eason Gender:Male Department:Civil Engineering ID:9487943
#Rank:B (Initial Score:78.2)