Polymorphism and Polymorphism
duck type
Polymorphism and Polymorphism
Polymorphism: A kind of thing has many forms. For example, animals have many forms, people, dogs, pigs, leopards. Water also has many forms, ice, snow, water vapor.
1 #Polymorphism : multiple forms of the same thing 2 import abc 3 class Animal(metaclass=abc.ABCMeta): #The same thing: animal 4 @abc.abstractmethod 5 def talk(self): 6 pass 7 8 class People (Animal): #Animal form one: human 9 def talk(self): 10 print ( ' say hello ' ) 11 12 class Dog(Animal): #Animal form two: dog 13 def talk(self): 14 print (' say wangwang ' ) 15 16 class Pig(Animal): #Animal form 3: Pig 17 def talk(self): 18 print ( ' say aoao ' ) 19 20 class Cat(Animal): 21 def talk(self) : 22 print ( ' say miamiao ' ) 23 24 #Polymorphism : It means that the object can be used directly without considering the type of the object 25 peo1= People() 26 dog1= Dog() 27 pig1= Pig( ) 28cat1= Cat() 29 30 # peo1.talk() 31 # dog1.talk() 32 # pig1.talk() 33 34 def func(animal): 35 animal.talk()
func(peo1) # don't care about peo1 Whether it is a pig dog or another type, it can be called and executed directly through this unified func function.
The benefits of polymorphism:
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
Duck Type:
That is, if it looks like a duck, walks like a duck and quacks like a duck, then it's a duck.
1 # Both are ducks, both look like files, so they can be used as files 2 class TxtFile: 3 def read(self): 4 print ( " text is reading " ) 5 6 def write(self ): 7 pass 8 9 class DiskFile: 10 def read(self): 11 print ( " disk is reading " ) 12 def write(self): 13 pass 14 15 text = TxtFile() 16 disk = DiskFile() 17 18 text.read() 19 disk.read()
Duck type, don't need to inherit abstract class, just write the method attributes in the two types similar. That's it.