Encapsulated Binding and Polymorphism

One: Properties

  A property is a special property that, when accessed, executes a piece of functionality (function) and returns a value

  Using this feature, the functional attributes of the class can be disguised as data attributes, making it more convenient to call


E.g

BMI index (bmi is calculated, but obviously it sounds like an attribute rather than a method, it is easier to understand if we make it an attribute)

  BMI values ​​for adults:
  Too light: below 18.5
  Normal: 18.5-23.9
  Overweight: 24-27
  Obesity: 28-32
  very obese, above 32
    Body mass index (BMI) = weight (kg) ÷ height ^ 2 (m)
    EX:70kg÷(1.75×1.75)=22.86
class People:
    def __init__(self,name,weight,height):
        self.name=name
        self.weight=weight
        self.height=height

egon=People('egon',75,1.80)

stay.bmi = stay.weight / (stay.height * stay.height)
print (egon.bmi)
# First need to be clear. bmi is calculated, not a fixed value, which means we have to write a function that will immediately calculate a value every time the function is called 
egon=People('egon',75,1.80)
yl=People('yangli ',85,1.74)
class People:
def __init__(self,name,weight,height):
self.name=name
self.weight=weight
self.height=height

def bmi(self):
return self.weight / (self.height * self.height)
# But obviously a person's bmi value sounds more like a noun than a verb 
# print(egon.bmi())
# print(yl.bmi())
class People:
def __init__(self,name,weight,height):
self.name=name
self.weight=weight
self.height=height

@property
def bmi(self):
return self.weight / (self.height * self.height)
# egon.weight=70 
# print(egon.bmi) #The essence of calling egon.bmi is to trigger the execution of the function bmi, so as to get its return value
# print(yl.bmi)
However, although bmi appears to be a property of the instantiated object, this is just a disguise, it's actually a function, so it's worth noting:
# egon.bmi=123 # The corresponding function behind egon.bmi is a function, so it cannot be assigned a value 
# del egon.bmi #It is essentially a function and cannot be deleted

. Why use property?
After defining a function of a class as a feature, when the object uses obj.name again, it is impossible to notice that its name is calculated by executing a function. The use of this feature follows the principle of unified access.

Two: Polymorphism

2.1 What is polymorphism?

  Polymorphism refers to multiple forms of a food

   Such as animals, there are cats, dogs, pigs and other forms

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

class Cat(Animal): #One of the forms of animals: cat
    def talk(self):
        print('say miaomiao')

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

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

2.2 Polymorphism

  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: pig, call (), cat. call (), pig call is "hum hum hum", cat meow is "meow meow meow", although the message of the two is the same, but the effect of execution is different

Polymorphism is divided into static polymorphism and dynamic polymorphism

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

  Dynamic polymorphism: as follows

cat=Cat()
dog=Dog()
pig=Pig()

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

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

2.3 Why use 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 

2.4 Duck types

  Duck type: i.e. if it looks like, and it quacks and walks like it, then it is 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
  , or you can create a completely new object that looks and behaves like it, but has nothing to do with it, the latter is often used to preserve loose coupling of program components.
# 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

Three: Object-oriented bound methods and unbound methods

3.1 The functions defined in the class are divided into two categories 

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

   The function defined inside the class is used by the object by default, and it is bound to the object, which is called the binding method of the 
object. The method of binding the object is special:
it should be called by the object. The object is automatically passed in as the first parameter

. The method bound to the class is special:
it should be called by the class, and the class will automatically pass in the class as the first parameter.

  Two: Unbound methods: methods decorated with staticmethod decorators

    It is an ordinary function feature: it is neither bound to a class nor an object, which means that anyone can use it, and whoever uses it is an ordinary function, which means that there is no automatic value transfer feature.

3.2 Binding method
  The method bound to the class (classmethod) 
  classmehtod is for the class, that is, bound to the class, the class will pass the class itself as a parameter to the first parameter of the class method when using it (even if it is called by an object, it will The class is passed in as the first parameter), python has built-in function classmethod for us to define the functions in the class as class methods  
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

3.3 Unbound methods

A method bound to a class (staticmethod) 
A method decorated with staticmethod inside the class is a waste binding method, which is an ordinary function statimethod that is not bound to a class or object, and can be called by anyone without automatic value transfer.
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(): # is a common tool
        m=hashlib.md5(str(time.time()).encode('utf-8'))
        return m.hexdigest()


print(MySQL.create_id) # <function MySQL.create_id at 0x0000000001E6B9D8 > #View the result as a normal function
conn=MySQL('127.0.0.1',3306)
print(conn.create_id) # <function MySQL.create_id at 0x00000000026FB9D8 > #View the result as a normal function
import settings
class MySQL:
    def __init__(self,host,port):
        self.host=host
        self.port=port

    @staticmethod
    def from_conf():
        return MySQL(settings.HOST,settings.PORT)

    # @classmethod #Which class to call, which class is passed in as the first parameter
    # def from_conf(cls):
    #     return cls(settings.HOST,settings.PORT)

    def __str__(self):
        return  ' I won't tell you '

class Mariadb(MySQL):
    def __str__(self):
        return '<%s:%s>' %(self.host,self.port)


m=Mariadb.from_conf()
print(m) #Our intention is to trigger Mariadb.__str__, but the result triggers the execution of MySQL.__str__, printing will not tell you:

mariadb is mysql

 





Guess you like

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