Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call a function after a class was loaded in python?

Tags:

python

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.

like image 776
Albert Tsai Avatar asked Oct 16 '25 14:10

Albert Tsai


1 Answers

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
like image 80
Lei Shi Avatar answered Oct 18 '25 09:10

Lei Shi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!