【发布时间】:2013-07-30 08:34:42
【问题描述】:
我希望装饰一个“可调用”类(定义了__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 类将有一个带有端口号的类属性,以便以后可以关闭服务。
【问题讨论】:
-
这与可调用的类无关。
标签: python decorator python-decorators callable