简体   繁体   English

Python 类将值传递给“self”

[英]Python Class passing value to “self”

I'm programming an optimizer that has to run through several possible variations.我正在编写一个优化器,它必须运行几种可能的变化。 The team wants to implement multithreading to get through those variants faster.该团队希望实现多线程以更快地处理这些变体。 This means I've had to put all my functions inside a thread-class.这意味着我必须将所有函数都放在一个线程类中。 My problem is with my call of the wrapper function我的问题是我对包装函数的调用

class variant_thread(threading.Thread):
    def __init__(self, name, variant, frequencies, fit_vals):
        threading.Thread.__init__(self)
        self.name = name
        self.elementCount = variant
        self.frequencies = frequencies
        self.fit_vals = fit_vals
    
    def run(self):
        print("Running Variant:", self.elementCount) # display thread currently running
        fitFunction = self.Wrapper_Function(self.elementCount)
    
        self.popt, pcov, self.infoRes = curve_fit_my(fitFunction, self.frequencies, self.fit_vals)

    def Optimize_Wrapper(self, frequencies, *params): # wrapper which returns values in manner which optimizer can work with
        cut = int(len(frequencies)/2) <---- ERROR OCCURS HERE
        freq = frequencies[:cut]
        vals = (stuff happens here)
        return (stuff in proper form for optimizer)

I've cut out as much as I could to simplify the example, and I hope you can understand what's going on.为了简化示例,我尽可能地删减了内容,希望您能理解发生了什么。 Essentially, after the thread is created it calls the optimizer.本质上,在创建线程后,它会调用优化器。 The optimizer sends the list of frequencies and the parameters it wants to change to the Optimize_Wrapper function.优化器将频率列表和它想要更改的参数发送到 Optimize_Wrapper 函数。

The problem is that Optimize-Wrapper takes the frequencies-list and saves them to "self".问题是 Optimize-Wrapper 获取频率列表并将它们保存到“self”。 This means that the "frequencies" variable becomes a single float value, as opposed to the list of floats it should be.这意味着“频率”变量变成了单个浮点值,而不是它应该是的浮点数列表。 Of course this throws an errorswhen I try to take len(frequencies).当然,当我尝试使用 len(frequencies) 时,这会引发错误。 Keep in mind I also need to use self later in the function, so I can't just create a static method.请记住,我还需要稍后在函数中使用 self,所以我不能只创建一个静态方法。

I've never had the problem that a class method saved any values to "self".我从来没有遇到过类方法将任何值保存到“self”的问题。 I know it has to be declared explicitly in Python, but anything I've ever passed to the class method always skips "self" and saves to my declared variables.我知道它必须在 Python 中显式声明,但是我传递给类方法的任何内容总是跳过“self”并保存到我声明的变量中。 What's going on here?这里发生了什么?

Don't pass instance variables to methods.不要将实例变量传递给方法。 They are already accessible through self .它们已经可以通过self访问。 And be careful about which variable is which.并注意哪个变量是哪个。 The first parameter to Wrapper_function is called "frequency", but you call it as self.Wrapper_Function(self.elementCount) - so you have a self.frequency and a frequency ... and they are different things. Wrapper_function的第一个参数称为“频率”,但您将其称为self.Wrapper_Function(self.elementCount) - 所以您有一个self.frequency和一个frequency ……它们是不同的东西。 Very confusing!非常混淆!

class variant_thread(threading.Thread):
    def __init__(self, name, variant, frequencies, fit_vals):
        threading.Thread.__init__(self)
        self.name = name
        self.elementCount = variant
        self.frequencies = frequencies
        self.fit_vals = fit_vals
    
    def run(self):
        print("Running Variant:", self.elementCount) # display thread currently running
        fitFunction = self.Wrapper_Function()
        self.popt, pcov, self.infoRes = curve_fit_my(fitFunction, self.frequencies, self.fit_vals)

    def Optimize_Wrapper(self): # wrapper which returns values in manner which optimizer can work with
        cut = int(len(self.frequencies)/2) <---- ERROR OCCURS HERE
        freq = self.frequencies[:cut]
        vals = (stuff happens here)
        return (stuff in proper form for optimizer)

You don't have to subclass Thread to run a thread.您不必子类化Thread来运行线程。 Its frequently easier to define a function and have Thread call that function.定义一个函数并让Thread调用该函数通常更容易。 In your case, you may be able to put the variant processing in a function and use a thread pool to run them.在您的情况下,您可以将变体处理放在一个函数中并使用线程池来运行它们。 This would save all the tedious handling of the thread object itself.这将节省线程对象本身的所有繁琐处理。

def run_variant(name, variant, frequencies, fit_vals):
    cut = int(len(self.frequencies)/2) <---- ERROR OCCURS HERE
    freq = self.frequencies[:cut]
    vals = (stuff happens here)
    proper_form = (stuff in proper form for optimizer)
    return curve_fit_my(fitFunction, self.frequencies, self.fit_vals)

if __name__ == "__main__":
    variants = (make the variants)
    name = "name"
    frequencies = (make the frequencies)
    fit_vals = (make the fit_vals)
    from multiprocessing.pool import ThreadPool
    with ThreadPool() as pool:
        for popt, pcov, infoRes in pool.starmap(run_variant,
                ((name, variant, frequencies, fit_vals) for variant in variants)):
            # do the other work here

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

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