复制实例中的函数

2024-06-28 19:11:21 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一些(简化的)代码:

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>

当我打电话的时候印刷体(),它将自我打印为代替。
但我想在我打电话的时候让赛尔夫代替我印刷体(),当我打电话的时候代替印刷品()
如果不在类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 = ""

Tags: instanceselfdefhaveclass印刷体inputstrcheckinput
2条回答

问题是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

但是在调用函数时仍然必须包含对象的实例。你知道吗

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

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

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

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

如果instOfA不需要存储的方法,可以将a的实例作为self传入:

instOfB.printSelf.__func__(instOfA)

相关问题 更多 >