我有以下代码:
class A:
def __init__(self):
self.a = "This is mine, "
def testfunc(self, arg1):
print self.a + arg1
class B:
def __init__(self):
self.b = "I didn't think so"
self.oldtestfunc = A.testfunc
A.testfunc = self.testfuncPatch
def testfuncPatch(self, arg):
newarg = arg + self.b # B instance 'self'
self.oldtestfunc(self, newarg) # A instance 'self'
instA = A()
instB = B()
instA.testfunc("keep away! ")
我想做以下事情:
有些类是由带参数的函数组成的。 我想把这个函数monkey补丁到类B中的一个函数上,做一些操作参数和访问类B的变量,我的问题是修补后的函数实际上需要两个不同的“self”对象,即类a的实例和类B的实例
这可能吗?在
如果
B
可以是A
的子类,那么问题就可以解决了。在问题是,当您使用已经绑定的方法重写类函数时,尝试绑定到其他实例时,只需忽略第二个实例:
因此,该方法基本上被视为
^{pr2}$staticmethod
,这意味着您必须以实例作为第一个参数来调用它:当我试图将
random.shuffle
直接导入一个类以使其成为一个方法时,我第一次遇到这个问题:为了解决这个问题,我创建了一个函数,它可以在第一个实例的基础上反弹到第二个实例:
因此,您可以很容易地将此应用于您的情况:
相关问题 更多 >
编程相关推荐