首页 技术 正文
技术 2022年11月21日
0 收藏 772 点赞 4,475 浏览 801 个字

多态:多态指的是一类事物有多种形态

多态性:

class Animal:

  def run(self):

    raise AtrributeError(“子类必须实现这种方法”)

class Person(Animal):

  pass

p = Person()

p.run()

通过父类主动抛出一个异常,告诉你子类中必须自己要写这个方法

改子类如下

class Person(Animal):

  def run(self):

    print(“人跑”)

再定义几个子类

def Dog(Animal):

  def run(self):

    print(“狗跑”)

def Pig(Animal):

  def run(self):

    print(“猪跑”)

person = Person()

dog = Dog()

pig = Pig()

person.run()

dog.run()

pig.run()

上面这就是多态,同属一个父类,但是他们在run这个方法上表现出不能的形态,这就是多态。

那什么是多态性呢?

还是举电脑组装的例子

电脑主机生产商定义了电脑这个类

class Computer():

  def usb_run(self):

    raise AtrributeError(“USB设备自己要开发run方法”)

def usb_insert(obj):

  obj.run()

class KeyBoard(Computer):

  def usb_run(self):

    print(“键盘插入了”)

class Mouse(Computer):

  def usb_run(self):

    print(“鼠标插入了”)

k = KeyBoard()

m = Mouse()

usb_insert(k)

usb_insert(m)

简单理解就是定义了一个函数,函数里执行了多态的共同方法,

但是并不区分是哪个对象传送过来的,具体对象需要通过向函数传递参数实现,这种实现方法就是多态性。

    

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848