Python journey: object-oriented polymorphism, polymorphism

polymorphism

Polymorphism means that a kind of thing has multiple forms

eg: Animals come in many shapes: cats, dogs, pigs

 

class Animal:   #Animal class 
    def eat(self):   #eat pass def drink
         (self):   #drink pass def sleep(self ) : #sleep pass
    
        
    
        

class Cat(Animal):
     def jiao(self):
         print ( ' Meow Meow Meow ' )
 class Dog(Animal):
     def call(self):
         print ( ' Wang Wang Wang ' )
 class Pig(Animal):
     def han(self) :
         print ( ' hum hum ' )

c=Cat()
d=Dog()
p = Pig()
 #Polymorphism : You can directly use the method c.drink() under the object without considering the specific type of the object

d.drink()
p.drink()

c.sleep()
d.sleep()
p.sleep()

c.jiao()
d.call()
p.han ()

Files come in many forms: text files, executable files

import abc
 class File(metaclass=abc.ABCMeta): #The same kind of thing: file 
    @abc.abstractmethod
     def click(self):
         pass

class Text(File): #One of the forms of the file: text file 
    def click(self):
         print ( ' open file ' )

class ExeFile(File): #The second form of the file: executable file 
    def click(self):
         print ( ' execute file ' )

 

 

two polymorphisms

1. What is polymorphic dynamic binding (also called polymorphism when used in the context of inheritance)

Polymorphism is the use of instances regardless of their type

 

In object-oriented methods, polymorphism is generally expressed as follows: send the same message to different objects (!!!obj.func(): is the method func that calls obj, also known as sending a message func to obj) , different objects will have different behaviors (i.e. methods) when they are received. That is, each object can respond to common messages 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.

For example: teacher. The bell rang after class (), student. The bell rang after class (), the teacher performed the off-duty operation, and the student performed the after-school operation. Although the two messages are the same, the effect of the execution is different.
explain in detail

 

 

 

Polymorphism is divided into static and dynamic polymorphism

  Static polymorphism: For example, any type can be operated with operator +

  Dynamic polymorphism: as follows

c=Cat()
d=Dog()
p = Pig()
 # c, d, p are all animals, as long as they are animals, there must be a talk method 
# So we can directly use c.drink() without considering the specific types of the three

d.drink()
p.drink()
# Further, we can define a uniform interface to use 
def func(obj):
    obj.talk()

2 Why use polymorphism (the benefits of polymorphism)

In fact, you can see from the above example of polymorphism that we have not added any new knowledge, that is to say, python itself supports polymorphism. What are the benefits of doing so?

1. Increased program flexibility

  In order to keep the same, regardless of the ever-changing object, the user calls it in the same form, such as func(animal)

2. Increased program scalability

  A new class is created by inheriting the animal class, and users do not need to change their own code, or use func(animal) to call     

The development of a program in the company is basically completed by several programmers, so it is necessary to create a set of rules that are required to be followed.

Use the base class to create a set of unified rules and force subclasses to follow (implemented by abstract classes), so that you can directly use the methods under the object without considering the specific type of the object

How to use polymorphism

import abc #Import   the abc module to implement mandatory constraints on subclasses #Subclasses 
must have the methods of the parent class, otherwise the instance will be TypeError: Can't instantiate abstract class People with abstract methods eat
class Animal (metaclass=abc.ABCMeta): #Animal Class @abc.abstractmethod def eat (self): #eat pass @abc.abstractmethod def drink(self): # pass @abc.abstractmethod def sleep(self): # pass class Cat(Animal): def eat(self): #eat pass def drink (self): #drink pass def sleep(self): #sleep print ( ' cat sleeps ' ) class People (Animal): #newly added belongs to animals Another form of: cat def eat(self): pass def drink(self): pass def sleep(self): print ( ' people sleep ' ) def func(animal): #For users, their own code does not need to be changed at all animal.sleep() cat1=Cat() peo1 = People() #The example speaks a person func(peo1) #caller's sleep function func (cat1)

 

 

Three duck types

Funny moment:

  Python embraces duck typing, i.e. 'if it looks like, quacks and walks like a duck, then it's a duck'

Python programmers usually write programs based on this behavior. For example, if you want to write a custom version of an existing object, you can inherit from that object

It is also possible to create a completely new object that looks and behaves like, but has nothing to do with it, which is often used to preserve the loose coupling of program components.

Example 1: Take advantage of various 'file-like' objects defined in the standard library, although these objects work like files, they do not inherit the methods of the built-in file objects

 

#Both are like ducks, both look like files, so you can use 
class TxtFile like a file:
     def read(self):
         pass

    def write(self):
        pass

class DiskFile:
    def read(self):
        pass
    def write(self):
        pass

Example 2: In fact, everyone has been enjoying the benefits of polymorphism. For example, Python's sequence types have many forms: strings, lists, tuples, and polymorphism is reflected as follows

# str, list, tuple are all sequence types 
s=str( ' hello ' )
l=list([1,2,3])
t=tuple((4,5,6))

#We can use s,l,t 
s. __len__ () without considering the three types
l. __len__ ()
t. __len__ ()

len (s)
len (l)
below)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324497145&siteId=291194637
Recommended