Hello,

I would like to create a hierarchy classes, where the leaves have a 
special attribute called "producer_id". In addition, I would like to 
have a function that can give me back the class assigned to any 
producer_id value. I tried to implement this with a metaclass, but I 
failed. Please help me, what I did wrong?

Thanks,

   Laszlo


class ProducerHandlerType(type):
    producer_handlers = {}
    @classmethod
    def registerProducerHandler(cls,producer_id):
        ph = cls.producer_handlers
        if ph.has_key(producer_id):
            ccls = ph[producer_id]
            raise Exception("This producer already has a calculator: 
"+str(ccls))
        else:
            print "Registering "+str(cls)+" for producer_id=",producer_id
            ph[producer_id] = cls

    def __init__(cls,name,bases,dct):
        super(ProducerHandlerType,cls).__init__(cls,name,bases,dct)
        if hasattr(cls,'producer_id'):
            cls.registerProducerHandler(getattr(cls,'producer_id'))
        else:
            print "No producer_id for ",str(cls)
        

class A(ProducerHandlerType):
    pass

class B(A):
    producer_id = 1

class C(A):
    producer_id = 2

# Metaclass methods are not called above, and the line below prints an 
empty dict. :-(
print B.producer_handlers
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to