python base - the bound object-oriented method of unbound

# Function defined in the class divided into two categories, 
# a binding method (Bind to whom, who will automatically call itself as the first argument) 
#    1, bound to the methods of the class: method classmethod decorated with decorator. 
#        Objects can also be used out, still class as the first argument 
#    2, the method of binding to the object: not decorated in any decorator method 
#        Notice that if the class object method calls are not automatically pass value, you need to manually pass 
#        object itself. 
#    Class has only one, so the object will automatically pass out value class method, an object can have many, like the calling object method 
#    need to pass the object value 
class A: 
    @classmethod 
    DEF tell_class (CLS):
         # generally bound to the class the method of this write, do not write self, write CLS 
        Print (CLS)
     DEF tell_obj (Self):
         Print (Self) 
a = a ()
a.tell_class ()
a.tell_obj () 
A.tell_class () 
A.tell_obj (A) 
# Second, the non-binding method, the method staticmethod decorator decorative 
#    1, does not bind classes and objects, classes and objects can be called, but will not automatically pass the value of 
#        is equivalent to a normal function 
#    Note: there is no method decorator decoration is bound to an object's method 
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 an ordinary function
        hashlib.md5 = m (STR (the time.time ()). encode ( ' UTF-. 8 ' ))
         return m.hexdigest ()
 Print (MySQL.create_id) # <function MySQL.create_id AT 0x0000000001E6B9D8> # see the results for the general function 
Conn = the MySQL ( ' 127.0.0.1 ' , 3306 )
 Print (conn.create_id) # <function MySQL.create_id AT 0x00000000026FB9D8> # View result ordinary function

 

Guess you like

Origin www.cnblogs.com/cong12586/p/11366535.html