脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python面向对象之继承和多态用法分析

Python面向对象之继承和多态用法分析

2021-07-03 00:01feesland Python

这篇文章主要介绍了Python面向对象之继承和多态用法,结合实例形式分析了Python面向对象程序设计中继承与多态的原理及相关操作技巧,需要的朋友可以参考下

本文实例讲述了python面向对象之继承和多态用法。分享给大家供大家参考,具体如下:

python 类的继承和多态

python 类的继承

在oop(object oriented programming)程序设计中,当我们定义一个class的时候,可以从某个现有的class 继承,新的class称为子类(subclass),而被继承的class称为基类、父类或超类(base class、super class)。

我们先来定义一个class person,表示人,定义属性变量 name 及 sex (姓名和性别);

定义一个方法print_title():当sex是male时,print man;当sex 是female时,print woman。参考如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class person(object):
  def __init__(self,name,sex):
    self.name = name
    self.sex = sex
  def print_title(self):
    if self.sex == "male":
      print("man")
    elif self.sex == "female":
      print("woman")
class child(person):              # child 继承 person
  pass
may = child("may","female")
peter = person("peter","male")
print(may.name,may.sex,peter.name,peter.sex)  # 子类继承父类方法及属性
may.print_title()
peter.print_title()

而我们编写 child 类,完全可以继承 person 类(child 就是 person);使用 class subclass_name(baseclass_name) 来表示继承;

继承有什么好处?最大的好处是子类获得了父类的全部属性及功能。如下 child 类就可以直接使用父类的 print_title() 方法

实例化child的时候,子类继承了父类的构造函数,就需要提供父类person要求的两个属性变量 name 及 sex:

在继承关系中,如果一个实例的数据类型是某个子类,那它也可以被看做是父类(may 既是 child 又是 person)。但是,反过来就不行(peter 仅是 person,而不是child)。

继承还可以一级一级地继承下来,就好比从爷爷到爸爸、再到儿子这样的关系。而任何类,最终都可以追溯到根类object,这些继承关系看上去就像一颗倒着的树。比如如下的继承树:

Python面向对象之继承和多态用法分析

isinstance()   及  issubclass()

python 与其他语言不同点在于,当我们定义一个 class 的时候,我们实际上就定义了一种数据类型。我们定义的数据类型和python自带的数据类型,比如str、list、dict没什么两样。

python 有两个判断继承的函数:isinstance() 用于检查实例类型;issubclass() 用于检查类继承。参见下方示例:

?
1
2
3
4
5
6
7
8
9
10
11
class person(object):
  pass
class child(person):         # child 继承 person
  pass
may = child()
peter = person()
print(isinstance(may,child))     # true
print(isinstance(may,person))    # true
print(isinstance(peter,child))    # false
print(isinstance(peter,person))   # true
print(issubclass(child,person))   # true

python 类的多态

在说明多态是什么之前,我们在 child 类中重写 print_title() 方法:若为male,print boy;若为female,print girl

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class person(object):
  def __init__(self,name,sex):
    self.name = name
    self.sex = sex
  def print_title(self):
    if self.sex == "male":
      print("man")
    elif self.sex == "female":
      print("woman")
class child(person):        # child 继承 person
  def print_title(self):
    if self.sex == "male":
      print("boy")
    elif self.sex == "female":
      print("girl")
may = child("may","female")
peter = person("peter","male")
print(may.name,may.sex,peter.name,peter.sex)
may.print_title()
peter.print_title()

当子类和父类都存在相同的 print_title()方法时,子类的 print_title() 覆盖了父类的 print_title(),在代码运行时,会调用子类的 print_title()

这样,我们就获得了继承的另一个好处:多态

多态的好处就是,当我们需要传入更多的子类,例如新增 teenagers、grownups 等时,我们只需要继承 person 类型就可以了,而print_title()方法既可以直不重写(即使用person的),也可以重写一个特有的。这就是多态的意思。调用方只管调用,不管细节,而当我们新增一种person的子类时,只要确保新方法编写正确,而不用管原来的代码。这就是著名的“开闭”原则:

  • 对扩展开放(open for extension):允许子类重写方法函数
  • 对修改封闭(closed for modification):不重写,直接继承父类方法函数

子类重写构造函数

子类可以没有构造函数,表示同父类构造一致;子类也可重写构造函数;现在,我们需要在子类 child 中新增两个属性变量:mother 和 father,我们可以构造如下(建议子类调用父类的构造方法,参见后续代码):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class person(object):
  def __init__(self,name,sex):
  self.name = name
  self.sex = sex
class child(person):        # child 继承 person
  def __init__(self,name,sex,mother,father):
    self.name = name
    self.sex = sex
    self.mother = mother
    self.father = father
may = child("may","female","april","june")
print(may.name,may.sex,may.mother,may.father)
person

若父类构造函数包含很多属性,子类仅需新增1、2个,会有不少冗余的代码,这边,子类可对父类的构造方法进行调用,参考如下:

?
1
2
3
4
5
6
7
8
9
10
11
class person(object):
  def __init__(self,name,sex):
    self.name = name
    self.sex = sex
class child(person):             # child 继承 person
  def __init__(self,name,sex,mother,father):
    person.__init__(self,name,sex)    # 子类对父类的构造方法的调用
    self.mother = mother
    self.father = father
may = child("may","female","april","june")
print(may.name,may.sex,may.mother,may.father)

多重继承

多重继承的概念应该比较好理解,比如现在需要新建一个类 baby 继承 child , 可继承父类及父类上层类的属性及方法,优先使用层类近的方法,代码参考如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class person(object):
  def __init__(self,name,sex):
    self.name = name
    self.sex = sex
  def print_title(self):
    if self.sex == "male":
      print("man")
    elif self.sex == "female":
      print("woman")
class child(person):
  pass
class baby(child):
  pass
may = baby("may","female")    # 继承上上层父类的属性
print(may.name,may.sex)
may.print_title()         # 可使用上上层父类的方法
class child(person):
  def print_title(self):
    if self.sex == "male":
      print("boy")
    elif self.sex == "female":
      print("girl")
class baby(child):
  pass
may = baby("may","female")
may.print_title()        # 优先使用上层类的方法

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

原文链接:https://www.cnblogs.com/feeland/p/4419121.html

延伸 · 阅读

精彩推荐