2

这是我正在尝试做的一些(简化)代码:

class a:
    pass

class b:
    def printSelf(self):
        print self


instOfA = a()
instOfB = b()
instOfA.printSelf = instOfB.printSelf
instOfA.printSelf()
  <__main__.b instance at 0x0295D238>

当我调用 instOfA.printSelf() 时,它会将 self 打印为 instOfB。
但是当我调用 instOfA.printSelf() 时,我希望 self 成为 instOfA,而当我调用 instOfB.printSelf() 时,我希望自己成为 instOfB,如果
不在类 a 中手动定义 printSelf,我该怎么做呢?

对于那些想知道为什么我什至想做这样的事情的人,这里有一个更长的例子:

#Acts as a template for aInstance. I would have several aInstances that have common rules, which are defined by an instance of the aDefinition class (though I'd have multiple rule sets too)
class aDefinitionClass: 
    def setInput(self, val):
        self.inputStr = val
    def checkInputByLength(self):
        return len(self.inputStr) < 5
    def checkInputByCase(self):
        return self.inputStr == self.inputStr.upper()
    checkInput = checkInputByLength


class aInstance(aDefinition):
    inputStr = ""
    def __init__(self, ruleDefinition):
        self.checkInput = ruleDefinition.checkInput


aDef = aDefinitionClass()
aDef.checkInput = aDef.checkInputByCase #Changing one of the rules.
aInst = aInstance(aDef)
aInst.setInput("ABC")
aInst.checkInput()
  AttributeError: aDefinitionClass instance has no attribute 'inputStr'

我意识到这有点不寻常,但我想不出另一种方法。我正在有效地尝试子类化一个实例。如果 Python 允许,它看起来像这样:

class aInstance(aDef):
    inputStr = ""
4

2 回答 2

2

您可以使用方法的描述符来获取绑定方法:

instOfA.printSelf = b.printSelf.__get__(instOfA)

当然,__class__如果你不知道 instOfB 的类型也可以使用:

instOfA.printSelf = instOfB.__class__.printSelf.__get__(instOfA)

如果instOfA不需要存储的方法,您可以传入aas的实例self

instOfB.printSelf.__func__(instOfA)
于 2010-01-25T03:01:30.463 回答
0

问题是这instOfB.printSelf是一个绑定方法-self当您创建对象时,变量设置为 instOfB 。坦率地说,我会做的只是稍微不同地设置功能:

class b:
    def printSelf(self, other):
        print other

然后你只需做

instOfA = a()
instOfB = b()
instOfA.printSelf = instOfB.printSelf
instOfA.printSelf(instOfA)

如果你想用 instOfB 做到这一点:

instOfB.printSelf(instOfB)

这种方式稍微丑陋一些,但它比 Brian 的解决方案更清洁和更明显(也可以正常工作)。

编辑:

更好的方法是使用描述符(尽管这仍然需要修改您的代码):

class b:
    @staticmethod
    def printSelf(self):
        print self

尽管在调用函数时仍然必须包含对象的实例。

于 2010-01-25T04:18:35.277 回答