欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

老生常谈python之鸭子类和多态

时间:2021-01-28 10:26:06|栏目:Python代码|点击:

一、 什么是多态

<1>一种类型具有多种类型的能力
<2>允许不同的对象对同一消息做出灵活的反应
<3>以一种通用的方式对待个使用的对象
<4>非动态语言必须通过继承和接口的方式来实现

二、 python中的多态

<1>通过继承实现多态(子类可以作为父类来使用)
<2>子类通过重载父类的方法实现多态

class Animal:
  def move(self):
    print('animal is moving....')
class Dog(Animal):
  pass
def move(obj):
  obj.move()

>>>move(Animal())
>>>animal is moving....
>>>move(Dog())
>>>animal is moving....

class Fish(Animal):
  def move(self):
    print('fish is moving....')
>>>move(Fish())
>>>fish is moving....

三、 动态语言和鸭子类型

<1>变量绑定的类型是不确定的

<2>函数和方法可以接收任何类型的参数

<3>调用方法时不检查提供的参数类型

<4>调用是否成功有参数的方法和属性确定,调用不成功则抛出错误

<5>不用实现接口

class P:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __add__(self, oth):
    return P(self.x+oth.x, self.y+oth.y)
  def info(self):
    print(self.x, self.y)
class D(P):
  def __init__(self, x, y, z):
    super.__init__(x, y)
    self.z = z

  def __add__(self, oth):
    return D(self.x+oth.x, self.y+oth.y, self.z+oth.z)
  def info(self):
    print(self.x, self.y, self.z)

class F:
  def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z

  def __add__(self, oth):
    return D(self.x+oth.x, self.y+oth.y, self.z+oth.z)
  
  def info(self):
    print(self.x, self.y, self.z)
  

def add(a, b):
  return a + b

if __name__ == '__main__':
  add(p(1, 2), p(3, 4).info())
  add(D(1, 2, 3), D(1, 2, 3).info())
  add(F(2, 3, 4), D(2, 3, 4).info())

四、 多态的好处

<1>可实现开放的扩展和修改的封闭

<2>使python程序更加的灵活

上一篇:Python制作简易版小工具之计算天数的实现思路

栏    目:Python代码

下一篇:对python中的os.getpid()和os.fork()函数详解

本文标题:老生常谈python之鸭子类和多态

本文地址:http://www.codeinn.net/misctech/52820.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有