Python object-oriented binding method and non-binding method

Bound and unbound methods

The functions defined in the class are divided into two categories: bound methods and unbound methods

The binding methods are divided into object methods bound to objects and class methods bound to classes.

Binding method: The special thing is that the caller itself is automatically passed as the first parameter

# 1. The method bound to the object: the caller is an object, and the object is automatically passed in. 
# 2. The method bound to the class: the caller class, the automatically passed in is the class

The function normally defined in the class is bound to the object by default, and after adding a decorator @classmethod to a function, the function is bound to the class.

We have already introduced object methods in previous chapters. In this section we mainly introduce class methods. Class methods are usually used to provide additional ways to initialize instances based on __init__

Example 1:

# Configuration file settings.py content 
HOST = ' 127.0.0.1 ' 
PORT = 3306

# Application class methods 
Import Settings

class Mysql:
    def __init__(self,ip,port):
        self.ip=ip
        self.port=port

    def func(self):
        print('%s:%s' %(self.ip,self.port))

    @classmethod # The following function bound to a method of decorated class 
    DEF from_conf (CLS):    # read configuration from a configuration file to initialize 
        # Print (CLS) 
        return CLS (settings.IP, settings.PORT)    # == > Mysql (settings.IP, settings.PORT) and then pass it to init to initialize

# OBJ1 Mysql = ( '1.1.1.1', 3306) 

obj2 = Mysql.from_conf ()    # calling a class method, the class is automatically passed to the first parameter as MySQL CLS 
Print (obj2. The __dict__ )
 Print (obj2.ip, obj2.port)

'''
{'ip': '127.0.0.0', 'port': 3306}
127.0.0.0 3306
'''

Example 2:

class Data_test2(object):
    day=0
    month=0
    year=0
    def __init__(self,year=0,month=0,day=0):
        self.day=day
        self.month=month
        self.year=year

    @classmethod
    DEF get_date (cls, string_date):
         # where the first parameter is cls, called the current class name represents 
        year, month The, Day Map = (int, string_date.split ( ' - ' ))
        date1 = cls (year, month, day)
         # What is returned is an initialized class 
        return date1

    def out_date(self):
        print("year :",self.year)
        print("month :",self.month)
        print("day :",self.day)


r=Data_test2.get_date("2016-8-6")
r.out_date()

'''
year : 2016
month : 8
day : 6
'''
View Code

The method bound to the class is specifically for the class, but in fact, the object can also be called, but the first parameter automatically passed in is still the class, that is to say, such a call is meaningless, and it is easy to cause confusion. This is also one of the differences between Python's object system and other object-oriented language object systems. For example, in Smalltalk and Ruby, the methods bound to classes are strictly separated from the methods bound to objects.

Unbound method:

After adding a decorator @staticmethod to a function in the class, the function becomes an unbound method, also known as a static method. This method is not bound to a class or object, both classes and objects can call it, but it is just an ordinary function, so there is no automatic value passing.

# A person who fails to bind to: the caller may be classes, objects, there is no automatic transfer of the effect of ginseng
class Mysql:
    def __init__(self,ip,port):
        self.nid=self.create_id()
        self.ip=ip
        self.port=port

    @staticmethod # The following functions decorated as a static method 
    DEF create_id ():
         Import UUID
         return uuid.uuid4 ()

obj1=Mysql('1.1.1.1',3306)

# Static method, or for an object class for function calls are 
# Print (Mysql.create_id) # <function Mysql.create_id AT 0x0000022D50E237B8> 
# Print (obj1.create_id) # <function Mysql.create_id AT 0x0000022D50E237B8>

# Mysql.create_id (1,2,3) #It is a function through a class or object, so the create_id function needs to have several parameters and must pass several parameters 
# obj1.create_id (4,5,6)

print(Mysql.create_id())

Summarize the use of bound methods and unbound methods: if a function is needed in the class, the implementation code of the function is defined as an object method for the object , and it is defined as a class method for the class , without reference Classes or objects define them as static methods .

 

Guess you like

Origin www.cnblogs.com/baicai37/p/12674497.html