为什么双重被视为全球名称?

时间:2011-11-25 06:18:28

标签: python module nameerror

我已创建下面的代码,当我导入模块并尝试运行它时,我收到以下错误:

>>> import aiyoo
>>> aiyoo.bixidist(1,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "aiyoo.py", line 50, in bixidist
    currentDist = dist(X,Y,c)
  File "aiyoo.py", line 39, in dist
    distance = math.sqrt(math.pow((X-getLat(i)),2)+math.pow((Y-getLong(i)),2))
  File "aiyoo.py", line 28, in getLat
    xmlLat = double(xmlLat)
NameError: global name 'double' is not defined

使用double函数将XML的unicode输出转换为double作为后续函数的输入。所以我不明白为什么,它被认为是导入aiyoo模块时的名称。

这是模块,名为aiyoo.py:

import math
import urllib2
from xml.dom.minidom import parseString
file = urllib2.urlopen('http://profil.bixi.ca/data/bikeStations.xml')
data = file.read()
file.close()
dom = parseString(data)

#this is how you get the data
def getID(i):
    xmlID = dom.getElementsByTagName('id')[i].toxml()
    xmlID = xmlID.replace('<id>','').replace('</id>','')
    xmlID = int(xmlID)
    return xmlID

def getLat(i):
    xmlLat = dom.getElementsByTagName('lat')[i].toxml()
    xmlLat = xmlLat.replace('<lat>','').replace('</lat>','')
    xmlLat = double(xmlLat)
    return xmlLat

def getLong(i):
    xmlLong = dom.getElementsByTagName('long')[i].toxml()
    xmlLong = xmlLong.replace('<long>','').replace('</long>','')    
    xmlLong = double(xmlLong)
    return xmlLong

#this is how we find the distance for a given station
def dist(X,Y,i):
    distance = math.sqrt(math.pow((X-getLat(i)),2)+math.pow((Y-getLong(i)),2))
    return distance

#this is how we find the closest station
def bixidist(X,Y):
     #counter for the lowest
    lowDist = 100000
    lowIndex = 0
    c = 0
    end = len(dom.getElementsByTagName('name'))
    for c in range(0,end):
            currentDist = dist(X,Y,c)
            if currentDist < lowDist:
                lowIndex = c
                lowDist = currentDist
    return getID(lowIndex)

4 个答案:

答案 0 :(得分:3)

正如其他人所回答的,double不是python中的内置类型。您必须使用float代替。浮点数在C [ref]中使用double实现。

关于你问题的主要部分,即“为什么双重考虑全局名称?”,当你使用variable-namedouble时,在当地情境中找不到,下一个查找是在全局上下文中。然后,如果即使在全局范围内也找不到它,则会引发异常,说NameError: global name 'double' is not defined

快乐编码。

答案 1 :(得分:1)

Python中没有double类型。如果您查看错误,它会抱怨它找不到任何名为double的内容。 Python中的浮点类型名为float

答案 2 :(得分:0)

应为xmlLat = float(xmlLat)

Python float与其他语言的double相同。 (64位)

http://codepad.org/AayFYhEd

答案 3 :(得分:0)

与目前为止所说的其他2个答案一样,Python没有double变量类型,而是float

现在针对您的标题中的问题以及可能是您的另一个混乱来源。解释器说“NameError:全局名称'double'未定义”的原因是因为Python搜索函数,变量,对象等的名称。这种模式由Python的命名空间和范围规则描述。因为您试图在函数内调用不存在的函数Double而不对其进行限定(即。SomeObject.Double(x)),所以Python首先在本地名称空间中查找该名称的对象(当前函数的名称空间,正在运行),然后是封闭函数的本地命名空间,然后是全局命名空间,最后是内置命名空间。解释器给你这条消息的原因是因为Python搜索Double()定义的顺序。全局命名空间是它在内置插件中查找之前检查的最后一个位置(这是Python的编码,而不是你的编码,所以我想解释器说“NameError:内置名称'double'是没有意义的没有定义”)。至少我认为这是正在发生的事情。我仍然不是一个经验丰富的程序员,所以我相信如果我出错了,别人会纠正我。