NameError:未定义全局名称'primes_dict'---在另一个导入的模块中定义?

时间:2012-11-24 01:34:09

标签: python variables global

我有两个模块:“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_dictpFactors(n)无效。

如何在另一个模块中使用字典primes_dict(在一个模块中创建)?提前谢谢。

1 个答案:

答案 0 :(得分:2)

primes中定义的任何内容都将以您import的名称命名。由于您将其导入p,因此primes_dict可以p.primes_dict访问。如果你愿意,你可以做

from primes import primes_dict

将其作为顶级名称。

相关问题