Sobhan
Sobhan

Reputation: 31

How to bypass a method in Python..?

Here is the scenario.

I have a class(X) having a method xyz

I have to define a class(Y) which extends class(X) but should run 'xyz' of class Y instead of 'xyz' of class X.

Here is the example :

Code in first.py :

class X():
    def xyz(self):
        -----

Code in second.py:

import first
class Y(X):
    def xyz(self):
        -----

Actually, my requirement is to call "Y.xyz()" whenever "X.xyz()" is called and I can't do modifications in 'first.py' but I can modify 'second.py'.

Could anyone please clarify this.

Upvotes: 0

Views: 1800

Answers (2)

justhalf
justhalf

Reputation: 9117

Converting is something like:

class X:
    def xyz(self):
        print 'X'

class Y(X):
    def __init__(self,x_instance):
        super(type(x_instance))

    def xyz(self):
        print 'Y'

def main():
    x_instance = X()
    x_instance.xyz()
    y_instance = Y(x_instance)
    y_instance.xyz()

if __name__=='__main__':
    main()

Which will produce:

X
Y

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123420

You are looking to monkeypatch.

Don't create a subclass, replace the xyz method directly on X:

from first import X

original_xyz = X.xyz

def new_xyz(self):
    original = original_xyz(self)
    return original + ' new information'

X.xyz = new_xyz

Replacing the whole class is possible too, but needs to be done early (before other modules have imported the class):

import first

first.X = Y

Upvotes: 2

Related Questions