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

yipeiwu_com6年前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 requests模块实例用法

1、Requests模块说明 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。 Python 标准库中的 u...

pytorch神经网络之卷积层与全连接层参数的设置方法

当使用pytorch写网络结构的时候,本人发现在卷积层与第一个全连接层的全连接层的input_features不知道该写多少?一开始本人的做法是对着pytorch官网的公式推,但是总是算...

tensorflow ckpt模型和pb模型获取节点名称,及ckpt转pb模型实例

ckpt from tensorflow.python import pywrap_tensorflow checkpoint_path = 'model.ckpt-8000'...

Python使用sklearn库实现的各种分类算法简单应用小结

本文实例讲述了Python使用sklearn库实现的各种分类算法简单应用。分享给大家供大家参考,具体如下: KNN from sklearn.neighbors import KNe...

python 根据时间来生成唯一的字符串方法

我们很多时候,特别是在生成任务的时候,都需要一个唯一标识字符串来标识这个任务,比较常用的有生成uuid或者通过时间来生成。uuid的话可以直接通过uuid模块来生成。如果是时间的话,可以...