Object-oriented (4) polymorphism and polymorphism,

polymorphism

Polymorphism literally means multiple forms of things

#Animals come in many shapes

import abc
 class Animal(metaclass=abc.ABCMeta): #The same kind of thing: animal 
    @abc.abstractmethod
     def talk(self):
         pass

class People(Animal): #One of the forms of animals: people 
    def talk(self):
         print ( ' say hello ' )

class Dog(Animal): #Animal form II: dog 
    def talk(self):
         print ( ' say wangwang ' )

class Pig(Animal): #The third form of animal: pig 
    def talk(self):
         print ( ' say aoao ' )

 

#Files   also 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 ' )

polymorphism

Methods that can be used directly on an object without considering any type of the object

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 polymorphism and dynamic polymorphism

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

  Dynamic polymorphism: as follows

peo=People()
dog=Dog()
pig=Pig()

# peo, dog, and pig are all animals, as long as they are animals, there must be a talk method 
# So we can use peo.talk() directly without considering the specific types of the three

dog.talk()
pig.talk()

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

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 

>>> class Cat(Animal): #Another form of animal: cat 
...      def talk(self):
...         print('say miao')
...
>>> def func(animal): #For users, their own code does not need to be changed at all 
... animal.talk()
...
>>> cat1=Cat() #Example a cat 
>>> func(cat1) #You can call the cat's talk function without changing the calling method 
say miao

'''
In this way, we have added a new form Cat, the instance cat1 generated by the Cat class, users can completely do not need to modify their own code. Call the talk method of cat1 in the same way as people, dogs, and pigs, that is, func(cat1)
''

duck type  

       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.

Bound and unbound methods

One: Binding method (who is bound to, whoever calls it will automatically pass in itself as the first parameter):

    1. A method bound to a class: a method decorated with the classmethod decorator.

                Tailored for class

                Class.boud_method(), which automatically passes the class as the first parameter

              (In fact, the object can also be called, but the class is still passed in as the first parameter)

    2. A method bound to an object: a method that is not decorated by any decorator.

               Tailored to Objects

               Object.boud_method(), automatically pass the object as the first parameter

             (A function belonging to a class can be called by the class, but it must be done according to the rules of the function. There is no automatic value transfer.)

A method bound to a class (classmethod)

  classmehtod is for classes, that is, bound to the class. When the class is used, the class itself will be passed as a parameter to the first parameter of the class method (even if it is called by an object, the class will be passed in as the first parameter) ), python has built-in function classmethod for us to define the functions in the class as class methods

HOST= ' 127.0.0.1 ' 
PORT =3306 
DB_PATH = r'C :\Users\Administrator\PycharmProjects\test\Object Oriented Programming\test1\db '
setting.py
import settings
class MySQL:
    def __init__(self,host,port):
        self.host=host
        self.port=port

    @classmethod
    def from_conf(cls):
        print(cls)
        return cls(settings.HOST,settings.PORT)

print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>>
conn=MySQL.from_conf()

conn.from_conf() #The object can also be called, but the first parameter passed by default is still the class

Two: Unbound methods: methods decorated with staticmethod decorators

        1. Not bound to classes or objects, both classes and objects can be called, but there is no such thing as automatic value transfer. It's just an ordinary tool

    Note: Different from the method bound to the object, the function defined directly in the class, which is not decorated by any decorator, is a method bound to the object, not an ordinary function. The object will automatically pass a value when calling this method. And the method decorated by staticmethod, no matter who calls it, there is no automatic value transfer.

A function decorated with staticmethod inside a class is an unbound method, which is a normal function

Statimethod is not bound to classes or objects, anyone can call it, and there is no automatic value transfer effect

import hashlib
import time
class MySQL:
    def __init__(self,host,port):
        self.id=self.create_id()
        self.host=host
        self.port=port
    @staticmethod
    def create_id(): #就是一个普通工具
        m=hashlib.md5(str(time.time()).encode('utf-8'))
        return m.hexdigest()


print(MySQL.create_id) #<function MySQL.create_id at 0x0000000001E6B9D8> #查看结果为普通函数
conn=MySQL('127.0.0.1',3306)
print(conn.create_id) #<function MySQL.create_id at 0x00000000026FB9D8> #查看结果为普通函数

 

Guess you like

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