将类中的方法替换为其

2024-04-29 07:05:56 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我不能在不同的模块(B)中修改或直接导入类(在模块a中定义),比如:

模块A部分:

class Tester(ParentHere):

   def run():
      print 100
      super(Tester, self).run()

如果我有权访问对象,如何覆盖run()方法?你知道吗

比如我有

模块B部分:

tester = factory.GetTester()
tester.run = some_method_here

如果无法直接导入Tester类或在模块A中修改其原始定义,如何在此处定义some_method_here以使用super(Tester, self).run()调用父类?你知道吗

例如:

def some_method_here():
    print '200 instead but do not print 100'
    super(Tester, self).run()

Tags: 模块runselfhere定义defsomemethod
2条回答

some_method_here中,添加将在super()调用中使用的参数tester

def some_method_here(tester):
    print '200 instead but do not print 100'
    super(type(tester), tester).run()

然后,要获得插入了正确的tester参数的callable,请执行以下操作:

from functools import partial

tester = factory.GetTester()

tester_method_here = partial(some_method_here, type=tester)

tester.run = tester_method_here

仍然可以使用实例的__class__属性获取对Tester的引用。所以在some_method_here内部,您可以调用super(self.__class__, self).run(),然后运行自己的代码。这样,每当对该特定对象调用run时,它仍将执行Tester.run中的所有代码以及您在函数中添加的任何内容。你知道吗

def some_method_here(self):
    # execute all your code ...
    print '200 instead but do not print 100'
    super(self.__class__, self).run()

但是在您的示例中,当它调用super时,它仍然会打印100,因为您是在自己的代码之后执行Tester.run。你知道吗

也就是说,你会看到的

200 instead but do not print 100
100

在日志中。你知道吗

如果您只希望它打印200行(即不执行Tester.run中的代码),那么首先不要调用super。你知道吗

而且,super只在调用从object继承的类时起作用,所以请注意这一点。如果Tester不是从对象继承的,则不能对其调用super。你知道吗


顺便说一下,您不能使用tester.run = some_method_here直接分配方法,因为some_method_here不会接收self参数。您必须使用types模块执行tester.run = types.MethodType(some_method_here, tester)。你知道吗

相关问题 更多 >