I want to register classes to a manager after class was loaded, like http handlers register to a handler manager.
It can be done in other ways, such as define the relationship in a map or call a register function after class definition.
But is there a better way to do this automatically?
update:
While Dunes's answer filled my need. I'm trying to improve the question and make it more useful for others who meet the same problem.
Here are the examples.
handler/__init__.py
handler/basehandler.py - classBase, HandlerManager
handler/handlerA.py - classA(classBase)
handler/hanlderB.py - classB(classBase)
handlerA and handlerB contains classA and classB, which are subclasses of classBase.
classA handlers requests from /a/, classB handlers /b/
I need to register them to HandlerManager automatically at the first time the handler module is imported.
If "being loaded" here means "being imported" (at the first time), then class decorator is an solution. Below sample code is copied from this page
registry = {}
def register(cls):
registry[cls.__clsid__] = cls
return cls
@register
class Foo(object):
__clsid__ = "123-456"
def bar(self):
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With