繁体   English   中英

如何在Python中配置装饰器

[英]How to configure a decorator in Python

我正在尝试使用Thespian( https://thespianpy.com/doc/ ),这是用于actor模型的Python库,尤其是我正在尝试使用“剧团”功能。 据我了解,团队装饰器充当调度程序,以运行多个actor达到指定的max_count,每个actor并行运行。 剧团功能被用作我的actor类上的装饰器:

@troupe(max_count = 4, idle_count = 2)
class Calculation(ActorTypeDispatcher):
    def receiveMsg_CalcMsg(self, msg, sender):
        self.send(sender, long_process(msg.index, msg.value, msg.status_cb))

我想在运行时而不是设计时配置max_count。 我承认我对装饰者的基本知识很薄弱。

如何在运行时将值传递给max_count?

我经历了这些,但是我仍然处于黑暗中:

python是否允许我在运行时将动态变量传递给装饰器?

http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/

根据到目前为止的答案,我尝试了此操作,但是未应用装饰器(即,它的作用就好像没有装饰器一样)。 我在类上方注释了@troupe实现,该方法(包括变量)工作正常。 这种方法不是:

# @troupe(max_count=cores, idle_count=2)
class Calculation(ActorTypeDispatcher):
    def receiveMsg_CalcMsg(self, msg, sender):
        self.send(sender, long_process(msg.index, msg.value, msg.status_cb))

def calculate(asys, calc_values, status_cb):
    decorated_class = troupe(max_count=5, idle_count=2)(Calculation)
    calc_actor = asys.createActor(decorated_class)

calculate函数中还有其他内容,但这几乎只是一些记账。

装饰器语法只是将函数应用于类的快捷方式。 一旦知道max_count的值,就可以使该函数自己调用。

class Calculation(ActorTypeDispatcher):
    ...

# Time passes

c = input("Max count: ")
Calculation = troupe(max_count=int(c), idle_count=2)(Calculation)

(或者,干脆等到c定义之前Calculation ,如所示@brunns 。)

应该很简单:


my_max = get_max_from_config_or_wherever()

@troupe(max_count = my_max, idle_count = 2)
class Calculation(ActorTypeDispatcher):
    ...

要记住的是, classdef语句本身是执行的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM