Binding methods and unbound methods of Python functions
Binding methods and unbound methods of Python functions
One binding method
Functions defined in classes 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.
Functions normally defined in a class are bound to the object by default. After adding the decorator @classmethod to a function, the function is bound to the class.
This chapter mainly introduces class methods. Class methods are usually used to provide additional ways to initialize instances based on init.
2. HOST='127.0.0.1'
3. PORT=3306
4.
5. # Application of class methods
6. import settings
7. class MySQL.
8. def __init__(self,host,port).
9. self.host=host
10. self.port=port
11. @classmethod
12. def from_conf(cls): # Initialize by reading configuration from the config file
13. return cls(settings.HOST,settings.PORT)
14.
15. >>> MySQL.from_conf # Bind to class method
16. <bound method MySQL.from_conf of <class '__main__.MySQL'>>
17. >>> conn=MySQL.from_conf() # Call class method, automatically pass class MySQL as first argument to cls
The method bound to a 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, which means that this kind of call is meaningless and can easily 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 , methods bound to classes and methods bound to objects are strictly separated.
Two non-binding methods
After adding the decorator @staticmethod to a function in a class , the function becomes an unbound method, also known as a static method. This method is not bound to a class or object. It can be called by both classes and objects, but it is just an ordinary function, so there is no automatic value transfer.
2. class MySQL:
3. def __init__(self,host,port):
4. self.id=self.create_id()
5. self.host=host
6. self.port=port
7. @staticmethod
8. def create_id():
9. return uuid.uuid1()
10.
11. >>> conn=MySQL(‘127.0.0.1',3306)
12. >>> print(conn.id) #100365f6-8ae0-11e7-a51e-0088653ea1ec
13. 14. # Classes or objects to call create_id find that it's all ordinary functions, not methods that are bound to anyone
15. >>> MySQL.create_id
16. <function MySQL.create_id at 0x1025c16a8>
17. >>> conn.create_id
18. <function MySQL.create_id at 0x1025c16a8>
To summarize the use of bound methods and unbound methods: If a function is needed in a class, and the implementation code of the function needs to reference an object, it will be defined as an object method. If it needs to reference a class, it will be defined as a class method. There is no need to reference the class. Or object, define it as a static method.