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 (2)/programming

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

The fun never stops!

class Object (object):
    __metaclass__ = Metaclass
class Metaclass (type):
    def __init__(cls, name, bases, *args, **kwargs):
        type.__init__(cls, name, bases, *args, **kwargs)
        cls.__new__ = staticmethod(cls.new)

        abstractmethods = []
        for clsname, clst in cls.__dict__.items():
            if isinstance(clst, AbstractMethod):
                abstractmethods.append(clsname)

        abstractmethods.sort()
        setattr(cls, '__abstractmethods__', abstractmethods)

    def new(self, cls):
        if len(cls.__abstractmethods__):
            raise NotImplementedError('Can\'t instantiate class `' + \
                                      cls.__name__ + '\';\n' + \
                                      'Abstract methods: ' + \
                                      ", ".join(cls.__abstractmethods__))

        return object.__new__(self)
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 21, in main
    b = MyAbstractObject()
  File "/home/ivo/p/python/abstract-classes/Metaclass.py", line 29, in new
    raise NotImplementedError('Can\'t instantiate class `' + \
NotImplementedError: Can't instantiate class `MyAbstractObject';
Abstract methods: foo