The following editor will bring you an old-fashioned talk about duck classes and polymorphism in python. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look
1. What is polymorphism
##<1>One type has multiple types Ability<2>Allows different objects to react flexibly to the same message
<3>Treat each used object in a common way
<4>Non-dynamic languages must pass Implemented through inheritance and interfaces
2. Polymorphism in 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....
3. Dynamic language and Duck typing
<1>The type of variable binding is undefinedclass 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. The benefits of polymorphism
< ;1> It can realize open expansion and closed modification<2>Make python program more flexibleThe above is the detailed content of Share examples of duck classes and polymorphism in Python. For more information, please follow other related articles on the PHP Chinese website!