我有两个模块:“factors.py”和“primes.py”。在“factors.pyc”中,我有一个应该找到数字的所有素因子的函数。在其中,我从“primes.py”导入2个函数。我在“primes.py”中有一个字典,它被声明为全局(在定义之前)。当我尝试在“factors.py”的代码中使用它时,我收到此错误:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pFactors(250)
File "D:\my_stuff\Google Drive\Modules\factors.py", line 53, in pFactors
for i in primes_dict:
NameError: global name 'primes_dict' is not defined
以下是我的代码:
在“factors.py”中:
def pFactors(n):
import primes as p
from math import sqrt
from time import time
pFact, primes, start, limit, check, num = [], [], time(), int(round(sqrt(n))), 2, n
if p.isPrime(n):
pFact = [1, n]
else:
p.prevPrimes(limit)
for i in primes_dict:
if primes_dict[i]:
primes.append(i)
#other code
在“primes.py”中:
def prevPrimes(n):
if type(n) != int and type(n) != long:
raise TypeError("Argument <n> accepts only <type 'int'> or <type 'long'>")
if n < 2:
raise ValueError("Argument <n> accepts only integers greater than 1")
from time import time
global primes_dict
start, primes_dict, num = time(), {}, 0
for i in range(2, n + 1):
primes_dict[i] = True
for i in primes_dict:
if primes_dict[i]:
num = 2
while (num * i < n):
primes_dict[num*i] = False
num += 1
end = time()
print round((end - start), 4), ' seconds'
return primes_dict #I added this in based off of an answer on another question, but it still was unable to solve my issue
prevPrimes(n)
以预期的方式运作。但是,由于我无法访问primes_dict
,pFactors(n)
无效。
如何在另一个模块中使用字典primes_dict
(在一个模块中创建)?提前谢谢。
答案 0 :(得分:2)
primes
中定义的任何内容都将以您import
的名称命名。由于您将其导入p
,因此primes_dict
可以p.primes_dict
访问。如果你愿意,你可以做
from primes import primes_dict
将其作为顶级名称。