绑定和非绑定方法的区别 [英] Difference Between Bound and Unbound Method
本文介绍了绑定和非绑定方法的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好朋友,
我定义了一个如下课程
Hello Friends,
I defined a class like below
class Robot:
def func(self):
self.Num = 20
我输入的shell上的
:
on the shell i typed:
>>> print Robot.func
所以我得到如下输出:
So i got the output like below:
<unbound method Robot.func>
然后我再次输入:
Then i again typed:
>>> r = Robot()
>> r.func.im_self.func
这次我得到了:
This time i got:
<bound method Robot.func of <__main__.Robot instance at 0x0000000002F81E48>>
如果看到输出,你会注意到一个绑定和一个未绑定关键字。
2之间有什么区别?
谢谢和问候,>
Rahul
If you see the outputs, you will notice a "Bound" and an "Unbound" keyword.
What is the difference between the 2?
Thanks and Regards,
Rahul
推荐答案
当您在类本身上调用func
时 -Robot.func
- 你有一个由Python自动创建的未绑定对象...它实际上意味着你正在执行一个没有任何类型/实例绑定的方法(它是2.x之间的变化和3.x-in 2.x有一种类型检查,即使是这种类型的方法调用...)。
当你在一个实例上调用方法时,你会得到一个方法调用那个例子。 Python将您对r.func
的调用转换为Robot.func(r)
,其中r是实例。在这种情况下,有一种类型检查(即使在3.x中)以确保函数和实例匹配...
When you callfunc
on the class itself -Robot.func
- you got a unbound object automatically created by Python...It actually means that you are executing a method without any bound to any type/instance (it is a change between 2.x and 3.x -in 2.x there was a type checking even for this type of method call...).
When you call the method on an instance you get a method call that bounded to that instance. Python translate your call ofr.func
toRobot.func(r)
, where r is the instance. In this case there is a type checking (even in 3.x) to ensure that the function and the instance are match...
这篇关于绑定和非绑定方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文