Home >Backend Development >Python Tutorial >Share examples of duck classes and polymorphism in Python
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
##f35d6e602fd7d0f0edfa6f7d103c1b57One type has multiple types Ability2cc198a1d5eb0d3eb508d858c9f5cbdbAllows different objects to react flexibly to the same message
5bdf4c78156c7953567bb5a0aef2fc53Treat each used object in a common way
23889872c2e8594e0f446a471a78ec4cNon-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
f35d6e602fd7d0f0edfa6f7d103c1b57The 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 modification2cc198a1d5eb0d3eb508d858c9f5cbdbMake 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!