Object-Oriented Programming (Bound and Unbound Methods of Classes)

Link https://www.cnblogs.com/vipchenwei/p/7126772.html

 

1. Object binding method

 

1. All the methods and functions in the class are bound to the object for use;

2. Binding methods have the function of automatically passing values. The value passed in is the object itself.

3. If the class wants to call the bound method, it must follow the parameter rules of the function. If there are several parameters, several parameters must be passed.

 

2. The binding method of the class

The methods in the class are bound to the object by default. When the object calls the bound method, the object will be automatically passed in as the first parameter; and the class is called, it must follow the one-to-one correspondence rule of function parameters. Several parameters, you must pass several parameters. If a method uses the @classmethod decorator, then the method is bound to the class. Whether it is called by an object or a class, the class will be passed in as the first parameter.

 

3. Unbound method @staticmethod

Python provides us with @staticmethod, which can unbind and turn a method in a class into an ordinary function.

Below, let's take a look at the code example:

# -*- coding: utf-8 -*-
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(): # It 's just a common tool 
        m=hashlib.md5(str(time.clock()).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) # <fun

#output _
<function MySQL.create_id at 0x000001D240CD1268>
<function MySQL.create_id at 0x000001D240CD1268>

From the above output, we can see that if a function is decorated with @staticmethod, then this function is no different from a normal function. Since it is an ordinary function, it follows the function parameter passing rules, and there are several parameters to pass several parameters.

Guess you like

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