Abstract methods in python
Posted on January 22nd, 2004 by ivo
Classes are fun!
class AbstractMethod (object):
def __init__(self, func):
self._function = func
def __get__(self, obj, type):
return self.AbstractMethodHelper(self._function, type)
class AbstractMethodHelper (object):
def __init__(self, func, cls):
self._function = func
self._class = cls
def __call__(self, *args, **kwargs):
raise TypeError('Abstract method `' + self._class.__name__ \
+ '.' + self._function + '\' called')
class MyAbstractObject (object):
foo = AbstractMethod('foo')
class MyObject (MyAbstractObject):
def foo(self):
print 'foo'
def main():
a = MyObject()
a.foo()
b = MyAbstractObject()
b.foo()
> python test.py
foo
Traceback (most recent call last):
File "test.py", line 25, in ?
main()
File "test.py", line 22, in main
b.foo()
File "/home/ivo/p/python/abstract-classes/AbstractMethod.py", line 19, in __call__
raise TypeError('Abstract method `' + self._class.__name__ \
TypeError: Abstract method `MyAbstractObject.foo' called