First, the binding method
1. methods to bind to a class: The method of decorating with the Classmethod adorner. Tailor-made for the class
Class. Boud_method (), which automatically passes a class as the first parameter
(The object can also be called, but the class is still passed in as the first parameter)
2. methods bound to an object: There is no way to decorate the adorner. Tailor-made for objects
Object. Boud_method (), automatically passes an object as the first parameter
(a function that belongs to a class.) The class can be called, but must follow the rules of the function, without automatically passing a value.
host='127.0.0.1'PORT=3306db_path=r'\ C Users\administrator\pycharmprojects\test\ Object-Oriented programming \test1\db'
View Code
ImportSettingsclassMySQL:def __init__(self,host,port): Self.host=host Self.port=Port @classmethoddeffrom_conf (CLS):Print(CLS)returnCLS (Settings. Host,settings. PORT)Print(mysql.from_conf)#<bound method Mysql.from_conf of <class ' __main__. MySQL ' >>conn=mysql.from_conf () conn.from_conf ( )#object can also be called, but the first parameter passed by default is still a class
View Code
Two, non-binding method: Decorate with Staticmethod ornament method
1. Do not bind to classes or objects, classes and objects can be called, but not automatically passed the value of the word, it's just a generic tool.
Note: Separate from bound to object methods, functions directly defined in the class, not decorated by any adorner, are bound to the object's method, not the normal function, the object calls the method will automatically pass the value, and the method of Staticmethod decoration, no matter who uses it, there is no automatic value to say
ImportHashlibImport TimeclassMySQL:def __init__(self,host,port): Self.id=self.create_id () self.host=host Self.port=Port @staticmethoddefCREATE_ID ():#It 's a common tool .M=HASHLIB.MD5 (str (time.time ()). Encode ('Utf-8')) returnm.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> #查看结果为普通函数Copy Code
View Code
The difference between Classmethod and Staticmethod
ImportSettingsclassMySQL:def __init__(self,host,port): Self.host=host Self.port=Port @staticmethoddeffrom_conf ():returnMySQL (settings. Host,settings. PORT)#@classmethod #哪个类来调用, which class is passed in as the first argument #def from_conf (CLS): #return CLS (settings. Host,settings. PORT) def __str__(self):return 'I won't tell you .'classMariadb (MySQL):def __str__(self):return '<%s:%s>'%(Self.host,self.port) m=mariadb.from_conf ()Print(m)#our intention is to trigger the mariadb.__str__, but the result triggers the execution of the mysql.__str__, and the print does not tell you:
View Code
Python Learning-----8.22--classmethod and Staticmethod