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

后端 未结 2 425
傲寒
傲寒 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 22:13

    The methods, even though calling the same object, are NOT the same object. You must test to see if the functions wrapped in the unbound method are the same object.

    I'm using 2.6 over here, so I also changed the class to inherit from object.

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

提交回复
热议问题