Navigation

home code debian images resume weblog wiki

Older news:

Dec 11, 2006:

Debian GNU/Linux

About lychnis.net
Jul 7, 2005:
Wanneer gebruik je -d en wanneer gebruik je -t?
Feb 18, 2005:
Mixing whitespace
Jan 10, 2005:
The difference between dogs and cats
Dec 22, 2004:
Sunrise in winter
Dec 12, 2004:
New site layout

Browse:


Abstract methods in python/programming

Posted on 2004-01-22 by ivo :: /programming :: link

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