溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python OOP面向?qū)ο缶幊倘绾螌?shí)現(xiàn)繼承

發(fā)布時間:2021-11-25 13:47:05 來源:億速云 閱讀:121 作者:小新 欄目:大數(shù)據(jù)

這篇文章將為大家詳細(xì)講解有關(guān)python OOP面向?qū)ο缶幊倘绾螌?shí)現(xiàn)繼承,小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

新建一個python文件命名為py3_oop4.py,在這個文件中進(jìn)行操作代碼編寫:

#面向?qū)ο缶幊?/code>#繼承
class Employee:  raise_amount = 1.04#定義列變量  def __init__(self,first,last,pay):    self.first = first    self.last = last    self.email = first + '.' + last +'@email.com'    self.pay = pay
 def fullname(self):    return '{} {}'.format(self.first,self.last)
 def apply_raise(self):    self.pay = int(self.pay * self.raise_amount)#定義子類Developer#繼承父類Employeeclass Developer(Employee):  raise_amount = 1.10  def __init__(self,first,last,pay,prog_lang):    #使用super繼承父類的__init__方法    super().__init__(first,last,pay)    #也可以用    #Employee.__init__(self,first,last,pay)    #不建議這種方式    self.prog_lang = prog_lang
dev_1 = Developer('T','Bag',50000,'Python')dev_2 = Developer('Mc','User',6000,'Java')print(dev_1.email)#T.Bag@email.comprint(dev_1.prog_lang)#Python#使用help查看Developer類的使用#print(help(dev_1))
#定義一個子類Managerclass Manager(Employee):  def __init__(self,first,last,pay,employees=None):    super().__init__(first,last,pay)    if employees is None:      employees = []    else:      self.employees = employees  #添加員工  def add_emp(self,emp):    if emp not in self.employees:      self.employees.append(emp)  #刪除員工  def remove_emp(self,emp):    if emp  in self.employees:      self.employees.remove(emp)
 #打印員工全名  def print_emps(self):    for emp in self.employees:      print('---->',emp.fullname())
mgr_1 = Manager('Su','DaQiang',100000,[dev_1])print(mgr_1.email)#Su.DaQiang@email.commgr_1.print_emps()#----> T Bagmgr_1.add_emp(dev_2)mgr_1.print_emps()#----> T Bag#----> Mc Usermgr_1.remove_emp(dev_2)mgr_1.print_emps()#----> T Bag
#使用內(nèi)置方法#isinstance():判斷實(shí)例#issubclass():判斷子類print(isinstance(mgr_1,Manager))print(isinstance(mgr_1,Employee))print(isinstance(mgr_1,Developer))print(issubclass(Developer,Employee))print(issubclass(Manager,Employee))print(issubclass(Manager,Developer))

運(yùn)行結(jié)果:

T.Bag@email.comPythonSu.DaQiang@email.com----> T Bag----> T Bag----> Mc User----> T BagTrueTrueFalseTrueTrueFalse

關(guān)于“python OOP面向?qū)ο缶幊倘绾螌?shí)現(xiàn)繼承”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI