How can a python base class determine if a subclass has overridden its methods?

Here is my hunch that doesn't work:

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) base_method = getattr(BaseClass, method) if this_method is not base_method: overriden.append(method) return overriden class SubClass(BaseClass): def foo(self): return 'override foo' o = SubClass() o.methods_implemented() 

Ideally, method_implemented () will return ['foo'].

How?

(Why do I want to do this? My base class is an HTTP resource class that has GET, POST methods, etc. By default they return 405 Method Not Implemented. It also has an OPTIONS method that should return a 200 s response heading Allow a set of methods that any subclass implements.)

+6
python
source share
2 answers

Perhaps it?

 >>> 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 to see if the object objects behind the associated methods are the same.

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

+9
source share

Methods, even when calling the same object, are NOT the same object. You should check if the functions wrapped in an unrelated method are the same object.

I use 2.6 here, so I also changed the inheritance class from the 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'] 
0
source share

All Articles