Skip to main content
 首页 » 编程设计

python之将方法绑定(bind)到另一个类

2024年11月01日6cmt

class A(object): 
 
    def a(self, b=1): 
        print 'Up' 
    d = {1 : a} 
 
    def b( self ): 
        print self.d[1] 
        print self.b 
        print self.d[1].__get__( self, A )() 
        # print self.d[1]() 
 
class B( object ): 
 
 
    def a( self ): 
        print 'here??' 
        return 10000 
    d = {1 : a} 
    def b( self ): 
        print 'hurray' 
 
o = A() 
o.b() 
 
b = B() 
type( o ).__dict__['b'].__get__( b, type( b ) )() 

大家好,

我正在浏览 Python: Bind an Unbound Method?和 http://users.rcn.com/python/download/Descriptor.htm并尝试对我的学习进行实验。

但是,我现在遇到了一些新的疑惑:-

  1. 在代码的最后一行,我可以使用 __get__与 b对象和实例:type(b) .这仅适用于方法 b在 class B 中定义.为什么会这样?
  2. 尽管最后一行要求我提供一个方法 b在class B ,还是方法b在 class A被调用。为什么会这样?
  3. 令我非常惊讶的是,在完成上述步骤之后,我注意到方法 a的 class A未被方法代码调用 b的 class A ;相反,它调用方法 a的 class B .为什么会这样?

看到这种行为后,我很困惑。我可能还需要了解更多关于描述符的知识。但是,如果你能回答我的疑惑,那将是一个很大的帮助

请您参考如下方法:

In the last line of my code, I'm able to use __get__ with b object and instance: type(b). This only works if method b is defined in class B. Why is it so?

你必须定义一个方法b在类里面B ,因为在 A.b你有print self.b .在这里,self是 B 类的一个实例,所以 self.b表示“属于此 b 的 B 方法”,而不是“属于此方法所在类的 b 方法”。如果删除 print self.b , 那么即使 B 代码也能正常工作没有b .

Even though the last line requires me to provide a method b in class B, still the method b in class A gets called. Why is it so?

A.b被调用是因为您正在使用 type( o ).__dict__['b'] 显式访问它.将该方法绑定(bind)到 A 实例还是 B 实例并不重要;还是A.b .

To my utter surprise, after the above step, I notice that the method a of class A is not called by the code of method b of class A; instead, it calls the method a of class B. Why is it so?

尽管b属于类A , self您传递给它的仍然是 B 的一个实例类(class)。您在 self 上访问的任何属性将是 B属性,以及您调用它的任何方法都将是 B方法。