我有两个模块:"factors.py“和"primes.py”。在"factors.pyc“中,我有一个函数,它应该找到一个数字的所有素因子。在它中,我从"primes.py“导入两个函数。我在"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 issueprevPrimes(n)以它想要的方式工作。但是,由于我无法访问primes_dict,所以pFactors(n)无法工作。
如何在另一个模块中使用字典primes_dict (在一个模块中创建)?提前谢谢。
发布于 2012-11-24 01:36:52
在primes中定义的任何内容都将以您import的名称命名。因为您以p的形式导入了它,所以primes_dict可以作为p.primes_dict访问。如果你愿意的话,你可以
from primes import primes_dict把它作为一个顶级的名字。
https://stackoverflow.com/questions/13537515
复制相似问题