我是python的新手,正在尝试使用pool.map()加载CPU。以下代码在不包含在类中时在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 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
我应该怎么做才能解决这个问题?
我是python的新手,正在尝试使用pool.map()加载CPU。以下代码在不包含在类def f(x)中时在CPU上进行加载:而True:x * x def load(...)>
您将这些方法视为静态类方法。这是修复代码的两种方法:
@staticmethod
。不太受欢迎的方法,使用类方法(不是面向对象的):