我正在寻找装饰一个“可调用”类(其中一个具有定义的__call__
方法),以便我可以在调用__init__
之前启动后台服务,并在调用本身之前传递参数以包含该服务已启动。如何用类装饰器来装饰“可调用”类?
因此,举例来说:
@init_service # starts service on port 5432
class Foo(object):
def __init__(self, port=9876):
# init here. 'port' should now be `5432` instead of the original `9876`
def __call__(self):
# calls the background service here, using port `5432`
func = Foo(port=9876)
...
result = func()
类init_service
将与端口号的一类属性,以便于以后的服务可以关机。
这有什么好做的类被调用。 –