NameError: name 'f' is not defined when using pool.map(f, range()) in class

NameError: name 'f' is not defined when using pool.map(f, range()) in class

我是 python 的新手,我正在尝试使用 pool.map() 加载 CPU。以下代码在 CPU 不包含在 class

中时加载 CPU
def f(x):
    while True:
        x*x

def load(cores):
    print('utilizing %d cores' % (cores/2))
    pool = Pool(10)
    pool.map(f, range(6))

但是,当我把它放在 class 中并尝试 运行 代码时

class test_cpu:

    def f(x):
        while True:
            x*x

    def load(cores):
        print('utilizing %d cores' % (cores/2))
        pool = Pool(10)
        pool.map(f, range(6))

if __name__ == '__main__':
    print('There are %d CPUs in your PC' % multiprocessing.cpu_count())
    cores_count = multiprocessing.cpu_count()
    input_user = input('What do you want to tes? type CPU, Memory or Both: ')
    input_user.lower()
    if input_user == 'cpu':
        test_cpu.load(cores_count)


当我键入 CPU 时,它会打印此错误,说明函数 f 未定义

utilizing 4 cores
Traceback (most recent call last):
  File "test_all.txt", line 81, in <module>
    test_cpu.load(cores_count)
  File "test_all.txt", line 45, in load
    pool.map(f, range(6))
NameError: name 'f' is not defined

我应该怎么做才能解决这个问题?

您将这些方法视为静态 class 方法。以下是修复代码的两种方法:

  1. 使用@staticmethod。不太喜欢的方法,使用 class 方法(非面向对象):
class test_cpu:
    @staticmethod  # changed
    def f(x):
        while True:
            x * x

    @staticmethod  # changed
    def load(cores):
        print("utilizing %d cores" % (cores / 2))
        pool = Pool(10)
        pool.map(test_cpu.f, range(6))  # changed
  1. 添加 self 并创建一个 test_cpu 实例:
import multiprocessing
from multiprocessing import Pool


class test_cpu:
    def f(self, x):  # changed
        while True:
            x * x

    def load(self, cores):  # changed
        print("utilizing %d cores" % (cores / 2))
        pool = Pool(10)
        pool.map(self.f, range(6))  # changed


if __name__ == "__main__":
    print("There are %d CPUs in your PC" % multiprocessing.cpu_count())
    cores_count = multiprocessing.cpu_count()
    input_user = input("What do you want to tes? type CPU, Memory or Both: ")
    input_user.lower()
    test_cpu_instance = test_cpu()  # changed
    if input_user == "cpu":
        test_cpu_instance.load(cores_count)  # changed