如何在 Python 中配置装饰器

Bri*_*ian 5 python python-decorators

我正在尝试使用 Thespian ( https://thespianpy.com/doc/ ),这是一个用于演员模型的 Python 库,特别是我正在尝试使用“剧团”功能。据我了解,剧团装饰器充当调度程序来运行多个演员,直到指定的 max_count,每个演员并行运行。剧团功能作为装饰器应用于我的演员类:

@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))
Run Code Online (Sandbox Code Playgroud)

我想在运行时配置 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)
Run Code Online (Sandbox Code Playgroud)

calculate函数中还有其他东西,但这几乎只是一些簿记。

che*_*ner 6

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

class Calculation(ActorTypeDispatcher):
    ...

# Time passes

c = input("Max count: ")
Calculation = troupe(max_count=int(c), idle_count=2)(Calculation)
Run Code Online (Sandbox Code Playgroud)

(或者,在定义之前只需等到你确实有,如@brunns 所示。)cCalculation


bru*_*nns 4

应该很简单:


my_max = get_max_from_config_or_wherever()

@troupe(max_count = my_max, idle_count = 2)
class Calculation(ActorTypeDispatcher):
    ...
Run Code Online (Sandbox Code Playgroud)

要记住的是classanddef语句本身是被执行的。

  • 在我的实验中,“my_max”的值是在导入时评估的,而不是在运行时...有什么方法可以改变这种行为,以便我可以在运行时更改 my_max 的值? (2认同)