I often talk about duck and Polymorphism in python, and I often talk about python polymorphism.
1. What is polymorphism?
<1> one type has multiple types of capabilities
<2> allow different objects to flexibly respond to the same message
<3> an object is treated in a common way.
<4> non-dynamic languages must be implemented through inheritance and interfaces.
2. polymorphism in python
<1> realize polymorphism through inheritance (sub-classes can be used as parent classes) <2> sub-classes implement multi-state class Animal: def move (self) by reloading the parent class ): print ('animal is moving .... ') class Dog (Animal): passdef 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 ....
Iii. Dynamic Language and duck type
<1> the variable binding type is uncertain.
<2> functions and methods can receive parameters of any type.
<3> when calling a method, the provided parameter types are not checked.
<4> whether the call is successful. If the call is unsuccessful, an error is thrown.
<5> no interface is required
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 + bif __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())
Iv. Benefits of Polymorphism
<1> openscaling and modification Sealing
<2> make python programs more flexible
The duck and Polymorphism in python are all the content shared by the editor. I hope you can give us a reference and support the house of helpers.