这是我正在尝试做的一些(简化)代码:
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 = ""