python's duck and polymorphism is a cliche

  • 2020-06-03 07:15:31
  • OfStack

1. What is polymorphism

< 1 > 1 type has multiple types of capabilities
< 2 > Allows different objects to react flexibly to the same 1 message
< 3 > Treat a used object in a general way
< 4 > Non-dynamic languages must be implemented through inheritance and interfaces

2. Polymorphism in python


<1> Implement polymorphism by inheritance (subclasses can be used as superclasses) 
<2> Subclasses implement polymorphism by overloading the methods of the parent class 

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....

3. Dynamic languages and duck types

< 1 > The type of variable binding is uncertain

< 2 > Functions and methods can accept any type of argument

< 3 > The method is called without checking the supplied parameter type

< 4 > Methods and properties that take parameters to determine whether the call is successful or not throw an error if the call is unsuccessful

< 5 > Not implementing an interface


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())

4. Advantages of polymorphism

< 1 > Can achieve open extension and modification of the closure

< 2 > Make python program more flexible


Related articles: