如何在Python中配置decorator

2024-09-24 02:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用spain(https://thespianpy.com/doc/),一个用于actor模型的Python库,特别是我正在尝试使用“剧团”功能。据我所知,couropedecorator充当调度程序来运行多个参与者,直到达到指定的最大\u计数,每个参与者并行运行。troupe功能在我的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))

我想在运行时配置最大\u计数,而不是在设计时。我承认我对装潢师的基础知识很薄弱。你知道吗

如何在运行时将值传递给max\u count?你知道吗

我已经经历了这些,但我仍然在黑暗中:

Does python allow me to pass dynamic variables to a decorator at runtime?

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

根据到目前为止的答案,我尝试了这个方法,但是没有应用decorator(也就是说,它的作用就像没有decorator一样)。我注释掉了类上面的@troube实现,该方法(包括变量)运行良好。这种方法不是:

# @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函数中还有其他一些东西,但这几乎只是一些簿记。你知道吗


Tags: 方法selfdefstatuscountmsgdecoratormax
2条回答

应该简单到:


my_max = get_max_from_config_or_wherever()

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

需要记住的是classdef语句本身是执行的。你知道吗

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

class Calculation(ActorTypeDispatcher):
    ...

# Time passes

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

(或者,在定义Calculation(如shown by @brunns)之前,只需等待您拥有c

相关问题 更多 >