这篇文章将为大家详细讲解有关python OOP面向对象编程如何实现继承,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
新建一个python文件命名为py3_oop4.py,在这个文件中进行操作代码编写:
#面向对象编程#继承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_langdev_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#使用内置方法#isinstance():判断实例#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))
运行结果:
T.Bag@email.comPythonSu.DaQiang@email.com----> T Bag----> T Bag----> Mc User----> T BagTrueTrueFalseTrueTrueFalse
关于“python OOP面向对象编程如何实现继承”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4592685/blog/4440546