【问题标题】:Is there a way to access an overridden method within a multiple inheritance object in Python?有没有办法在 Python 中访问多重继承对象中的重写方法?
【发布时间】:2013-01-15 10:29:06
【问题描述】:

我有以下 Python 代码。如何在不更改类定义的情况下让 c 返回 2?或者不同的说法。如何访问具有多重继承的对象中的覆盖方法?

class A(object):
    def foo(self):
        return 1

class B(object):
    def foo(self):
        return 2

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

c = C()
c.foo() # Returns 1

【问题讨论】:

  • 请将结果发布为您自己问题的答案。
  • 您将能够在 8 小时后将答案添加到您自己的问题中。
  • 完成,感谢您让我知道我应该单独回答。

标签: python multiple-inheritance


【解决方案1】:

在问了这个问题之后,我在其他地方得到了答案,所以这里是:

import types
c.foo = types.MethodType(B.foo, c)

【讨论】:

  • 只是指出你只是在改变对象c,而不是类。 C().foo() 仍然会返回 1。这真的是你想要的吗?
【解决方案2】:

你可以显式调用未绑定的方法:

>> B.foo(c)
2

【讨论】:

    猜你喜欢
    • 2011-12-06
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多