【问题标题】:How do I check if a method was overwritten by a child class?如何检查方法是否被子类覆盖?
【发布时间】:2020-04-06 04:00:12
【问题描述】:

我希望能够检查子类是否覆盖了方法。例如,

class Foo:
    def __init__(self):
        # Is there something following this sort of spec?
        print("overridden" if self.bar != Foo.bar else "not overridden")
    def bar(self):
        return 0

覆盖bar 的继承方法可能是:

class Kung(Foo):
    def __init__(self):
        super(Kung, self).__init__()
    def bar(self):
        return 1

在这种情况下,Kung() 应该打印“覆盖”,但 Foo() 应该打印“未覆盖”。 我可以检查bar 是否在Foo 的__init__ 中被覆盖而不检查返回值吗?

【问题讨论】:

    标签: python inheritance overriding introspection


    【解决方案1】:

    这是一件非常奇怪的事情。我质疑需要这样做的设计。无论如何,您可以检查以下内容:

    class Foo:
        def __init__(self):
            try:
                bar = type(self).bar
            except AttributeError:
                bar = None
            if bar is None or bar is Foo.bar:
                print("not overriden")
            else:
                print("overridden")
    
        def bar(self): return 0
    

    这有效,因为您正在检查 类对象 上的bar。如果您使用some_instance.some_method,那么会在每次调用时创建一个新方法对象,这就是您的方法行不通的原因。

    考虑:

    >>> class Foo:
    ...     def bar(self): pass
    ...
    >>> foo = Foo()
    >>> foo.bar is foo.bar
    False
    

    然而,

    >>> Foo.bar is Foo.bar
    True
    

    【讨论】:

    • 用例很奇怪。我有一个类似数据类的对象,它表示带有我想要保护的方法的参数解析器的参数。更多详情请访问github.com/swansonk14/typed-argument-parser/issues/12
    • 我认为我们最终将允许覆盖,并确保属性不会影响方法。不管怎样,这很有趣!
    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2021-12-15
    • 2020-06-27
    相关资源
    最近更新 更多