How can a python base class tell whether a sub class has overridden its methods?

后端 未结 2 427
傲寒
傲寒 2021-01-17 21:23

Here is my guess, which doesn\'t work:

class BaseClass(object):
    def foo(self):
        return \'foo\'
    def bar(self):
        return \'bar\'
    def m         


        
2条回答
  •  悲&欢浪女
    2021-01-17 21:56

    Perhaps this?

    >>> class BaseClass(object):
    ...     def foo(self):
    ...         return 'foo'
    ...     def bar(self):
    ...         return 'bar'
    ...     def methods_implemented(self):
    ...         """This does work."""
    ...         overriden = []
    ...         for method in ('foo', 'bar'):
    ...             this_method = getattr(self, method)
    ...             base_method = getattr(BaseClass, method)
    ...             if this_method.__func__ is not base_method.__func__:
    ...                 overriden.append(method)
    ...         return overriden
    ... 
    >>> class SubClass(BaseClass):
    ...     def foo(self):
    ...         return 'override foo'
    ... 
    >>> o = SubClass()
    >>> o.methods_implemented()
    ['foo']
    

    This checks whether the function objects behind the bound methods are the same.

    Note, prior to Python 2.6, the __func__ attribute was named im_func.

提交回复
热议问题