如何调用已被扩展方法覆盖的方法?

时间:2017-09-28 02:58:14

标签: python

我有一个plot方法的类,如下所示:

class A:
    def plot(self):
        ...

我写了一个像这样的扩展方法:

def plot(self):
    ...
    self.plot()

A.plot = plot

但这会产生递归调用。如何在不更改方法名称的情况下解决此问题?

2 个答案:

答案 0 :(得分:1)

保持其先前的值:

_plot = A.plot

def plot(self):
    _plot(self)

A.plot = plot

答案 1 :(得分:0)

您可以在课堂上使用猴子补丁,也可以只使用一个实例。请参阅以下smaple代码,setattr(A, 'method_to_patch', new_method_on_class)覆盖A类中定义的方法。因此,实例a和b中的method_to_override已经过修补。 TypeMethod只能修补实例。因此,只有实例a已被修补。

class A(object):
    def __init__(self):
        self.words = 'testing'

    def method_to_patch(self):
        print ('words: {}'.format(self.words))


def new_method_on_class(self):
    print ('class: patched and words: {}'.format(self.words))


def new_method_on_instance(self):
    print ('instance: patched and words: {}'.format(self.words))

a = A()
b = A()
a.method_to_patch()

setattr(A, 'method_to_patch', new_method_on_class)

a.method_to_patch()
b.method_to_patch()

a.method_to_patch = types.MethodType(new_method_on_instance, a)

a.method_to_patch()
b.method_to_patch()

输出:

  

字样:测试

     

class:patched and words:testing

     

class:patched and words:testing

     

实例:修补和单词:测试

     

class:patched and words:testing

相关问题