The examples in this article describe the class methods that are bound and unbound in Python. Share to everyone for your reference, as follows:
Like a function, a class method in Python is also an object. Because methods can be accessed either through an instance or through a class, there are two flavors in Python:
Unbound class method: no Self
Returns an unbound method object through a class that refers to a method. To invoke it, you must present an instance as the first parameter.
instance method of binding: Has self
Returns a bound method object through the instance access method. Python automatically binds an instance to a method, so we don't have to pass an instance argument when we call it.
Both methods are objects, which can be passed and stored in the list for waiting. Both runs require an instance as the first parameter (妤 a self value), but Python automatically provides one when a binding method is called through an instance. For example, we run the following code:
Class Test: def func (self,message): print messageobject1=test () x=object1.funcx (' Bind method object, instance is implied ') t= Test.funct (Object1, ' unbound method object, need to pass an instance ') #t (' unbound method object, need to pass an instance ') #错误的调用
Object1=test () generates an instance, Object1.func returns a bound method that binds the instance Object1 and the method func.
And Test.func is using the class to refer to the method, we get an unbound method object. To invoke it you have to pass an instance parameter, such as T (Object1, ' unbound method object, need to pass an instance ').
Most of the time, we call the method directly, so we generally don't notice the method object. However, if you start writing the code for a generic calling object, you need to pay particular attention to the unbound methods, which need to pass an instance parameter.