jajabarr
jajabarr

Reputation: 561

Class Method Swapping Keeping Old Class 'Self'?

I'm having trouble correctly function swapping between instance methods (python3).

Let's say I have SomeClass:

class SomeClass:

    def pSelf(self):
        # Do stuff with self.variables

In my particular case I have two implementations of this class, a correct version and a buggy version

Now I'll instantiate two objects of the type SomeClass (marked C for correct, B for buggy):

objOne = SomeClassC()
objTwo = SomeClassB()

I want objTwo to have the correct implementation of pSelf:

objTwo.pSelf = objOne.pSelf

However, objOne's method of pSelf is bound to objOne, so:

objTwo.pSelf() # This will do stuff with objOne.self!

I have tried to import type and perform the following:

objTwo.pSelf = types.MethodType(objOne.pSelf, objTwo)

As far as I can tell, this correctly binds the pSelf function to objTwo, however then I receive an incorrect argument error - presumably because objTwo.pSelf now receives two self arguments.

I'm at a loss on how to go about this, what is the correct way to swap functions between two (similar) classes?

Upvotes: 0

Views: 52

Answers (1)

Dan D.
Dan D.

Reputation: 74645

You need to get the function for the method before making a method out of it and some object

objTwo.pSelf = types.MethodType(objOne.pSelf.__func__, objTwo)

I would like to remark that this is a sign of a bad design.

Upvotes: 2

Related Questions