python - copying functions located in instances -
Here's some code (simplified) for what I'm doing: When I'd call instOfA.printSelf (), it prints Being instOfB themselves I know this is a bit unusual, but I can not think of a different way of doing this, I think effectively trying to subclass an example. This is something that has been shown in this way: Python allowed:
class A: Pass square b: def printSelf (self):. Print self instOfA = one () instOfB = b () instOfA.printSelf = instOfB.printSelf instOfA.printSelf () of & lt; Main example_____ at 0x0295D238 & Example;
But I self instOfA when I instOfA.printSelf (), And instOfB when I call instOfB.printSelf ()
How do I go about defining the printSelf in square one without having to do this manually?
To think of those people why I would like to do something like this, here is a long example:
Work as a template for # intense def setInput (Self, Val) :: I have many anInstances general rules, which are defined by an example of aDefinition class that class ADefinitionClass (although I would have many rules set too) checkInputByLength def self.inputStr = Val (manually ): Return Lane (self.inputStr) & lt; 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 # change the rules ainst = aInstance (aDef) aInst.setInput ( "ABC") aInst.checkInput () AttributeError: aDefinitionClass example has no properties 'inputStr'
< Div class = "text" itemprop = "text">
You can use the descriptor of the method to get a bound method:
instOfA.printSelf = b .printSelf get .__ __ (instOfA)
of course, you can use __ class __
if you do not know the type of instOfB,:
instOfA.printSelf = instOfB .__ class __. printSelf .__ get __ (instOfA)
If instOfA
does not need to be stored method, you can pass an example of just a as
self
:
instOfB.printSelf .__ function __ (instOfA)
Comments
Post a Comment