为什么我的@classmethod变量“未定义”?

时间:2016-07-27 16:51:52

标签: python object multiprocessing pool class-method

我目前正在Python 2.7中编写代码,其中涉及创建一个对象,其中我有两个类方法和其他常规方法。我需要使用这种特定的方法组合,因为我写的代码的上下文更大 - 这与这个问题无关,所以我不会深入探讨。

在我的__init__函数中,我正在创建一个Pool(一个多处理对象)。在创建时,我调用了一个setup函数。此设置功能是@classmethod。我通过使用cls.variablename语法在此设置函数中定义了一些变量。正如我所提到的,我在init函数中调用了这个setup函数(在Pool创建中),因此应根据我的理解创建这些变量。

稍后在我的代码中,我调用了一些其他函数,最终导致我在我之前讨论的同一个对象中调用另一个@classmethod(与第一个@classmethod相同的对象)。在这个@classmethod中,我尝试访问我在第一个@classmethod中创建的cls.variables。但是,Python告诉我,我的对象没有属性“cls.variable”(在这里使用通用名称,显然我的实际名称是特定于我的代码)。

无论如何......我意识到这可能很令人困惑。这里有一些(非常)通用的代码示例来说明相同的想法:

class General(object):
    def __init__(self, A):
        # this is correct syntax based on the resources I'm using,
        # so the format of argument isn't the issue, in case anyone
        # initially thinks that's the issue
        self.pool = Pool(processes = 4, initializer=self._setup, initargs= (A, )

    @classmethod
    def _setup(cls, A):
        cls.A = A

    #leaving out other functions here that are NOT class methods, just regular methods

    @classmethod
    def get_results(cls):
        print cls.A

当我到达print cls.A line的等价物时,我得到的错误是:

AttributeError: type object 'General' has no attribute 'A'

编辑以显示此代码的用法: 我在我的代码中调用它的方式是这样的:

G = General(5)
G.get_results()

所以,我正在创建一个对象实例(我在其中创建了Pool,它调用了setup函数),然后调用了get_results。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

主要流程中未定义General.A的原因是multiprocessing.Pool仅在进程中运行General._setup。这意味着它将在主进程中调用 not (您调用Pool)。

最终会有4个进程,其中每个进程都定义了General.A,但不在主进程中。您实际上并未像这样初始化游戏池(请参阅问题this answerHow to use initializer to set up my multiprocess pool?

你想要一个Object Pool,它在Python中不是本机的。 StackOverflow上有Python Implementation of the Object Pool Design Pattern个问题,但你可以通过在线搜索找到一堆。

相关问题