Home  >  Article  >  Backend Development  >  Detailed analysis of usage of bound and unbound class methods in Python

Detailed analysis of usage of bound and unbound class methods in Python

高洛峰
高洛峰Original
2017-03-06 13:45:281108browse

The examples in this article describe bound and unbound class methods in Python. Share it with everyone for your reference, as follows:

Like functions, class methods in Python are also objects. Since methods can be accessed both through instances and classes, there are two styles in Python:

Unbound class method: no self

passed Class to reference method returns an unbound method object. To call it, you must explicitly provide an instance as the first argument.

Bound instance method: There is self

Return a bound method object through the instance access method. Python automatically binds an instance to the method, so we don't need to pass an instance parameter when calling it.

Both methods are objects, they can be passed, stored in the list and waited. Both runtimes require an instance as the first argument (a self value), but Python automatically provides one when calling a bound method through an instance. For example, we run the following code:

class Test:
  def func(self,message):
    print message
object1=Test()
x=object1.func
x('绑定方法对象,实例是隐含的')
t=Test.func
t(object1,'未绑定的方法对象,需要传递一个实例') 
#t('未绑定的方法对象,需要传递一个实例') #错误的调用

object1=Test() generates an instance, object1.func returns a bound method, and combines the instance object1 and the method func binding.

And Test.func uses a class to reference a method, and we get an unbound method object. To call it, you must pass an instance parameter, such as t(object1,'Unbound method object, you need to pass an instance').

Most of the time, we call methods directly, so we generally don’t notice the method object. But if you start writing code that calls generic objects, you need to pay special attention to unbound methods, which require passing an instance parameter.

For more detailed analysis of usage of bound and unbound class methods in Python, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn