经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
Python3.5面向对象程序设计之类的继承和多态详解
来源:jb51  时间:2019/4/24 12:29:01  对本文有异议

本文实例讲述了Python3.5面向对象程序设计之类的继承和多态。分享给大家供大家参考,具体如下:

1、继承的定义

继承是指:可以使用现有类的所有功能,并在无需重新编写原来的类的情况下对这些功能进行扩展。
(1)通过继承创建的新类称为“子类”或“派生类”。
(2)被继承的类称为“基类”、“父类”或“超类”。
继承的过程,就是从一般到特殊的过程。要实现继承,可以通过“继承”(Inheritance)和“组合”(Composition)来实现。
在某些 OOP 语言中,一个子类可以继承多个基类。但是一般情况下,一个子类只能有一个基类,要实现多重继承,可以通过多级继承来实现。

2、继承的分类

继承概念的实现方式主要有2类:实现继承、接口继承。

(1) 实现继承是指使用基类的属性和方法而无需额外编码的能力;
  (2)接口继承是指仅使用属性和方法的名称、但是子类必须提供实现的能力(子类重构父类方法);
在考虑使用继承时,有一点需要注意,那就是两个类之间的关系应该是“属于”关系。
抽象类仅定义将由子类创建的一般属性和方法。
OO开发范式大致为:划分对象→抽象类→将类组织成为层次化结构(继承和合成) →用类与实例进行设计和实现几个阶段。

3、示例代码

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4.  
  5. #类的继承
  6. class People:
  7. def __init__(self,name,age):
  8. self.name = name
  9. self.age = age
  10.  
  11. def eat(self):
  12. print("%s is eating..." %self.name)
  13.  
  14. def sleep(self):
  15. print("%s is sleeping..." %self.name)
  16.  
  17. def talk(self):
  18. print("%s is talking..." %self.name)
  19.  
  20. class Man(People): #继承父类People类
  21. def make_money(self):
  22. print("%s is making money..." %self.name)
  23.  
  24. def sleep(self):
  25. People.sleep(self) #对父类方法的扩展
  26. print("man is sleeping...")
  27.  
  28. class Women(People):
  29. def shop(self):
  30. print("%s is shopping..." %self.name)
  31.  
  32. m1 = Man("Jack","20")
  33. m1.eat()
  34. m1.make_money()
  35. m1.sleep()
  36.  
  37. w1 = Women("Amy","25")
  38. w1.talk()
  39. w1.shop()

运行结果:

Jack is eating...
Jack is making money...
Jack is sleeping...
man is sleeping...
Amy is talking...
Amy is shopping...

4、子类中对父类的构造函数进行重构两种方法

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4.  
  5. #类的继承
  6. #class People: #经典类
  7. class People(object): #新式类
  8. def __init__(self,name,age):
  9. self.name = name
  10. self.age = age
  11.  
  12. def eat(self):
  13. print("%s is eating..." %self.name)
  14.  
  15. def sleep(self):
  16. print("%s is sleeping..." %self.name)
  17.  
  18. def talk(self):
  19. print("%s is talking..." %self.name)
  20.  
  21. class Man(People): #继承父类People类
  22. def __init__(self,name,age,money):
  23. #People.__init__(self,name,age) #(方法一)对构造函数进行重构、添加父类中没有的属性
  24. super(Man,self).__init__(name,age) #(方法二)利用super对构造函数进行重构(新式类写法)
  25. self.money = money
  26. print("%s have money %s$" %(self.name,self.money))
  27.  
  28. def make_money(self):
  29. print("%s is making money..." %self.name)
  30.  
  31. def sleep(self):
  32. People.sleep(self) #对父类方法的扩展
  33. print("man is sleeping...")
  34.  
  35. class Women(People):
  36. def shop(self):
  37. print("%s is shopping..." %self.name)
  38.  
  39. m1 = Man("Jack","20",10)
  40. m1.eat()
  41. m1.make_money()
  42. m1.sleep()
  43.  
  44. w1 = Women("Amy","25")
  45. w1.talk()
  46. w1.shop()

运行结果:

J ack have money 10$
Jack is eating...
Jack is making money...
Jack is sleeping...
man is sleeping...
Amy is talking...
Amy is shopping...

5、多继承方式

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4.  
  5. #类的继承
  6. #class People: #经典类
  7. class People(object): #新式类
  8. def __init__(self,name,age):
  9. self.name = name
  10. self.age = age
  11. self.friends = []
  12.  
  13. def eat(self):
  14. print("%s is eating..." %self.name)
  15.  
  16. def sleep(self):
  17. print("%s is sleeping..." %self.name)
  18.  
  19. def talk(self):
  20. print("%s is talking..." %self.name)
  21.  
  22. class Relationship(object):
  23. def make_friends(self,obj):
  24. print("%s is making friends with %s" %(self.name,obj.name))
  25. self.friends.append(obj)
  26.  
  27. class Man(People,Relationship): #多继承
  28. def __init__(self,name,age,money):
  29. #People.__init__(self,name,age) #(方法一)对构造函数进行重构、添加父类中没有的属性
  30. super(Man,self).__init__(name,age) #(方法二)利用super对构造函数进行重构(新式类写法)
  31. self.money = money
  32. print("%s have money %s$" %(self.name,self.money))
  33.  
  34. def make_money(self):
  35. print("%s is making money..." %self.name)
  36.  
  37. def sleep(self):
  38. People.sleep(self) #对父类方法的扩展
  39. print("man is sleeping...")
  40.  
  41. class Women(People,Relationship): #多继承
  42. def shop(self):
  43. print("%s is shopping..." %self.name)
  44.  
  45. m1 = Man("Jack","20",10)
  46.  
  47. w1 = Women("Amy","25")
  48.  
  49. m1.make_friends(w1)
  50. w1.name = "liu"
  51. print(m1.friends)

运行结果:

Jack have money 10$
Jack is making friends with Amy
[<__main__.Women object at 0x0057FA30>]

6、新式类与经典类的继承顺序

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4.  
  5. class A(object): #新式类
  6. def __init__(self):
  7. print("A")
  8.  
  9. class B(A):
  10. def __init__(self):
  11. print("B")
  12.  
  13. class C(A):
  14. def __init__(self):
  15. print("C")
  16.  
  17. class D(B,C):
  18. def __init__(self):
  19. pass
  20. #print("D")
  21.  
  22. obj = D()



7、继承示例——学校、教师与学生

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4.  
  5. #继承实例(新式类)——模拟学校、教师与学生
  6.  
  7. class School(object):
  8. def __init__(self,name,addr):
  9. self.name = name
  10. self.addr = addr
  11. self.students = []
  12. self.stuffs = []
  13.  
  14. def enroll(self,stu_obj): #学生注册
  15. print("%s 学员办理注册" %stu_obj.name)
  16. self.students.append(stu_obj)
  17.  
  18. def heir(self,staff_obj): #聘请教师
  19. print("聘请教师 %s" %staff_obj.name)
  20. self.stuffs.append(staff_obj)
  21.  
  22. class SchoolMember(object):
  23. def __init__(self,name,age,sex):
  24. self.name = name
  25. self.age = age
  26. self.sex = sex
  27.  
  28. def tell(self):
  29. pass
  30.  
  31. class Teacher(SchoolMember):
  32. def __init__(self,name,age,sex,salary,course):
  33. super(Teacher,self).__init__(name,age,sex)
  34. self.salary = salary
  35. self.course = course
  36.  
  37. def tell(self):
  38. print('''
  39. ----- info of Teacher:%s -----
  40. Name:%s
  41. Age:%s
  42. Sex:%s
  43. Salary:%s
  44. Course:%s
  45. '''%(self.name,self.name,self.age,self.sex,self.salary,self.course))
  46.  
  47. def teach(self):
  48. print("%s is teaching course [%s]" %(self.name,self.course))
  49.  
  50. class Student(SchoolMember):
  51. def __init__(self,name,age,sex,stu_id,grade):
  52. super(Student,self).__init__(name,age,sex)
  53. self.stu_id = stu_id
  54. self.grade = grade
  55.  
  56. def tell(self):
  57. print('''
  58. ----- info of Student:%s -----
  59. Name:%s
  60. Age:%s
  61. Sex:%s
  62. Stu_id:%s
  63. Grade:%s
  64. '''%(self.name,self.name,self.age,self.sex,self.stu_id,self.grade))
  65.  
  66. def pay_tuition(self,amount):
  67. print("%s has paied tuition for $%s" %(self.name,amount))
  68.  
  69. #实例化
  70. school = School("qinghua","beijing")
  71.  
  72. t1 = Teacher("Jack","30","M","20000","Python")
  73. t2 = Teacher("Amy","28","F","15000","Linux")
  74.  
  75. s1 = Student("liu","23","M","1701","Python")
  76. s2 = Student("wang","25","F","1702","Linux")
  77.  
  78. #调用显示学生与教师的信息
  79. t1.tell()
  80. s1.tell()
  81.  
  82. school.heir(t1) #聘请教师t1
  83. school.enroll(s1) #学生s1注册
  84. school.enroll(s2)
  85.  
  86. print(school.stuffs)
  87. print(school.students)
  88.  
  89. #聘请的第一位教师教课
  90. school.stuffs[0].teach()
  91. for stu in school.students:
  92. stu.pay_tuition(5000)
  93.  

运行结果:

        ----- info of Teacher:Jack -----
        Name:Jack
        Age:30
        Sex:M
        Salary:20000
        Course:Python
       
 
        ----- info of Student:liu -----
        Name:liu
        Age:23
        Sex:M
        Stu_id:1701
        Grade:Python
       
聘请教师 Jack
liu 学员办理注册
wang 学员办理注册
[<__main__.Teacher object at 0x0059FDB0>]
[<__main__.Student object at 0x0059FDF0>, <__main__.Student object at 0x0059FE10>]
Jack is teaching course [Python]
liu has paied tuition for $5000
wang has paied tuition for $5000

8、多态(polymorphisn)——一种接口,多种形态

(1)定义

多态性(polymorphisn)是允许你将父对象设置成为和一个或更多的他的子对象相等的技术,

赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作。

简单的说,就是一句话:允许将子类类型的指针赋值给父类类型的指针。

多态的作用:我们知道,封装可以隐藏实现细节,使得代码模块化;继承可以扩展已存在的代码模块(类);它们的目的都是为了——代码重用。

而多态则是为了实现另一个目的——接口重用!多态的作用,就是为了类在继承和派生的时候,保证使用“家谱”中任一类的实例的某一属性时的正确调用。

Pyhon 很多语法都是支持多态的,比如 len(),sorted(), 你给len传字符串就返回字符串的长度,传列表就返回列表长度。

(2)示例代码:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4.  
  5. class Animal(object):
  6. def __init__(self,name):
  7. self.name = name
  8.  
  9. def talk(self):
  10. raise NotImplementedError("Subclass must implement abstract method")
  11.  
  12. # 多态——一种接口,多种形态
  13. @staticmethod
  14. def animal_talk(obj):
  15. obj.talk()
  16.  
  17. class Cat(Animal):
  18. def talk(self):
  19. print("%s Meow!" %self.name)
  20.  
  21. class Dog(Animal):
  22. def talk(self):
  23. print("%s Woof! Woof!" % self.name)
  24.  
  25. d = Dog("A")
  26. #d.talk()
  27.  
  28. c = Cat("B")
  29. #c.talk()
  30.  
  31. #多态
  32. Animal.animal_talk(d)
  33. Animal.animal_talk(c)
  34.  

运行结果:

A Woof! Woof!
B Meow!

9、面向对象设计利器——领域建模

(1)定义

从领域模型开始,我们就开始了面向对象的分析和设计过程,可以说,领域模型是完成从需求分析到面向 对象设计的一座桥梁。 
领域模型,顾名思义,就是需求所涉及的领域的一个建模,更通俗的讲法是业务模型。

(2)领域模型有两个主要的作用:
发掘重要的业务领域概念
建立业务领域概念之间的关系 

 (3)领域建模三字经 
领域模型如此重要,领域建模的方法概括一下就是“找名词”! 即使是简单的找名词这样的操作,也涉及到分析和提炼,而 不是简单的摘取出来就可,

这种情况下分析师和设计师的经验和技能就能够派上用场了。但领域模型分析 也确实相对简单,即使没有丰富的经验和高超的技巧,至少也能完成一个能用的领域模型。

一个关键的问题:从哪里找? 因为领域模型是“需求到面向对象的桥梁”,能想到:从需求模型中找,具体来说就是从用例中找。 

归纳:领域建模的方法就是“从用例中找名词”。 当然,找到名词后,为了能够更加符合面向对象的要求和特点。

我们还需要对这些名词进一步完善,这就 是接下来的步骤:加属性,连关系!

最后我们总结出领域建模的三字经方法:找名词、加属性、连关系。 



更多关于Python相关内容感兴趣的读者可查看jb51专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号