首页 > 编程语言 > 详细

Python学习(七)面向对象 ——继承和多态

时间:2015-04-12 10:32:55      阅读:254      评论:0      收藏:0      [点我收藏+]

Python 类继承和多态

 

  在OOP(Object Oriented Programming)程序设计中,当我们定义一个class的时候,可以从某个现有的class 继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Super class)。

  我们先来定义一个class,名为Person,表示人,定义属性变量 name 及 sex (姓名和性别);定义一个方法:当sex是male时,print he;当sex 是female时,print she

  参考如下代码:

 1 class Person:
 2     def __init__(self,name,sex):
 3         self.name = name
 4         self.sex = sex
 5         
 6     def print_heorshe(self):
 7         if self.sex == "male":
 8             print("he")
 9         elif self.sex == "female":
10             print("she")
11 
12 May = Person("May","female")
13 Peter = Person("Peter","male")
14 
15 May.print_heorshe()
16 Peter.print_heorshe()

  当我们编写 Student 类的时候,完全可以继承 Person 类;使用 class subclass_name(baseclass_name) 来表示继承;

  继承有什么好处?最大的好处是子类获得了父类的全部功能。如下Student 类就可以直接使用父类的 print_heorshe 方法

  实例化Student的时候,子类需要提供父类Person要求的两个属性变量 name 及 sex

 1 class Person:
 2     def __init__(self,name,sex):
 3         self.name = name
 4         self.sex = sex
 5         
 6     def print_heorshe(self):
 7         if self.sex == "male":
 8             print("he")
 9         elif self.sex == "female":
10             print("she")
11 
12 class Student(Person):            # Student 继承 Person
13     pass
14 
15 May = Student("May","female")
16 Peter = Student("Peter","male")
17 
18 print(May.name,May.sex,Peter.name,Peter.sex)
19 May.print_heorshe()
20 Peter.print_heorshe()

 

Python学习(七)面向对象 ——继承和多态

原文:http://www.cnblogs.com/feeland/p/4419121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!