python类的多态、多态性

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

多态性:

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)

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

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

    

猜你喜欢

转载自www.cnblogs.com/laofang/p/12076802.html