On polymorphism in python

  • 2021-11-10 10:14:09
  • OfStack

Catalogue 1. Polymorphism 2. Polymorphism 3. Duck type

1. Polymorphism

Polymorphism refers to a class of things with multiple forms, such as animals, which can include cats, dogs, pigs and so on. (An abstract class has multiple subclasses, so the concept of polymorphism depends on inheritance.)


import abc
class Animal(metaclass=abc.ABCMeta): # Same as 1 Similar thing : Animals 
    @abc.abstractmethod
    def talk(self):
        pass

class Cat(Animal): # The form of animals 1: Cat 
    def talk(self):
        print('say miaomiao')

class Dog(Animal): # The form of animals 2: Dog 
    def talk(self):
        print('say wangwang')

class Pig(Animal): # The form of animals 3: Pig 
    def talk(self):
        print('say aoao')

2. Polymorphism

Note: Polymorphism and polymorphism are two concepts

Polymorphism means that functions with different functions can use the same function name, so that functions with different contents can be called with one function name. In the object-oriented method, polymorphism is generally expressed as follows: when the same message is sent to different objects, different objects will produce different behaviors (i.e. methods) when receiving it. In other words, each object can respond to a common message in its own way. The so-called message is to call a function, and different behaviors refer to different implementations, that is, to execute different functions.


import abc
class Animal(metaclass=abc.ABCMeta): # Same as 1 Similar thing : Animals 
    @abc.abstractmethod
    def talk(self):
        pass

class Cat(Animal): # The form of animals 1: Cat 
    def talk(self):
        print('say miaomiao')

class Dog(Animal): # The form of animals 2: Dog 
    def talk(self):
        print('say wangwang')

class Pig(Animal): # The form of animals 3: Pig 
    def talk(self):
        print('say aoao')

c = Cat()
d = Dog()
p = Pig()

def func(obj):
    obj.talk()

func(c)
func(d)
func(p)

------------------------------

>>> say miaomiao
>>> say wangwang
>>> say aoao

To sum up, polymorphism is: 1 interface, multiple implementations

Benefits of polymorphism:

Increased the flexibility of the program, in order to change, regardless of the ever-changing objects, users are the same form to call, such as func (obj) By inheriting the animal class, a new class is created. Users do not need to change their own code, or use func (obj) to call

3. Duck type

Calling different subclasses will produce different behaviors without knowing exactly what this subclass is actually, which is an important application scenario of polymorphism. In python, the polymorphism is not so cool because of the duck type (duck typing).

Duck type is a style of dynamic type. In this style, the valid semantics of an object are determined not by inheriting from a specific class or implementing a specific interface, but by the "current collection of methods and properties." The name of this concept comes from the duck test proposed by James Whitcomb Riley. "Duck test" can be expressed as follows: "When you see a bird walking like a duck, swimming like a duck and barking like a duck, then the bird can be called a duck."

In duck types, the focus is not on the type of the object itself, but on how it is used. For example, in a language that doesn't use duck type, we can write a function that accepts an object of type "duck" and calls its "walk" and "call" methods. In languages that use duck types, such a function can accept an object of any type and call its "walk" and "call" methods. If these methods that need to be called do not exist, a runtime error will be thrown. The behavior that any object with such correct "go" and "call" methods can be accepted by functions leads to the above statement, hence the name of this way of determining types.

Duck types usually benefit from not testing the types of parameters in methods and functions, but relying on documentation, clear code, and testing to ensure proper use.

The concept of Duck typing comes from the poem of James Whitcomb Riley (James Whitcomb Riley, 1849-1916) in Indiana, USA: "When I see bird that walks duck and duck and like like like like like like like a duck, I ES70that bird

First, the code is also from a classic case on the Internet:


class Duck():
    def walk(self):
         print('I walk like a duck')
    def swim(self):
         print('i swim like a duck')
 
class Person():
    def walk(self):
         print('this one walk like a duck') 
    def swim(self):
         print('this man swim like a duck')

It is obvious that the Person class has the same methods as the Duck class 1, when a function calls the Duck class and utilizes two methods, walk () and swim (). The Person class we passed in can also run. The function does not check whether the object type is Duck. As long as it has walk () and swim () methods, it can be called correctly.

For another example, if an object implements the __getitem__ method, the interpreter of python will treat it as an collection, and methods such as slicing and obtaining subitems can be used on this object; If an object implements the __iter__ and next methods, python considers it to be an iterator and loops on the object to get the subitems.

The above is to talk about the details of polymorphism in python. For more information about polymorphism in python, please pay attention to other related articles on this site!


Related articles: