1

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

>>> 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

4 回答 4

3

正如其他人回答的那样,double不是python中的内置类型。你必须使用,float而不是。浮点是在 C [ ref ] 中使用 double 实现的。

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

快乐编码。

于 2011-11-25T06:37:43.860 回答
1

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

于 2011-11-25T06:25:03.830 回答
0

它应该是xmlLat = float(xmlLat)

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

http://codepad.org/AayFYhEd

于 2011-11-25T06:23:38.770 回答
0

就像到目前为止的其他 2 个答案所说,Python 没有double变量类型,而是有float.

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

于 2011-11-25T07:10:10.420 回答