简体   繁体   English

如何在Python中绕过一个方法..?

[英]How to bypass a method in Python..?

Here is the scenario. 这是场景。

I have a class(X) having a method xyz 我有一个类(X)有一个方法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. 我必须定义一个扩展类(X)的类(Y),但是应该运行类Y的'xyz'而不是类X的'xyz'。

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'. 实际上,我的要求是每当调用“X.xyz()”时调用“Y.xyz()”并且我不能在'first.py'中进行修改但我可以修改'second.py'。

Could anyone please clarify this. 任何人都可以澄清一下。

You are looking to monkeypatch. 你正在寻找monkeypatch。

Don't create a subclass, replace the xyz method directly on X : 不要创建子类,直接在X上替换xyz方法:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM