为什么double被认为是全局名称?

2 投票
4 回答
8314 浏览
提问于 2025-04-17 07:02

我写了下面的代码,当我导入这个模块并尝试运行时,出现了以下错误:

>>> 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 转换成一个双精度浮点数,以便后面的函数可以使用。所以我不明白为什么在导入 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

就像之前的两个回答说的那样,Python没有double这种变量类型,它用的是float

现在来聊聊你标题里的问题,可能也是让你困惑的地方。解释一下为什么解释器会说“NameError: global name 'double' is not defined”。这其实跟Python是怎么查找函数、变量和对象的名字有关。这个过程可以用Python的命名空间和作用域规则来描述。因为你在一个函数里试图调用一个不存在的函数Double,但没有加上前缀(比如SomeObject.Double(x)),所以Python首先会在当前函数的局部命名空间里找这个名字,然后再去找外层函数的局部命名空间,接着是全局命名空间,最后才是内置命名空间。解释器给你这个提示的原因就是因为Python查找Double()定义的顺序。全局命名空间是它最后检查的地方,之后才会去找内置的命名空间(那些是Python自带的代码,而不是你写的,所以解释器不会说“NameError: built-in name 'double' is not defined”)。我觉得大概就是这样。我自己也不是很有经验的程序员,如果我说错了,希望其他人能纠正我。

2

在Python里没有叫做double的类型。如果你看到错误信息,它会说找不到叫double的东西。Python中的浮点数类型叫做float

3

正如其他人所说,double 不是 Python 里自带的类型。你需要用 float 来代替。在 C 语言中,浮点数是用 double 来实现的 [ 参考 ]。

至于你问题的重点,也就是“为什么 double 被认为是全局名称?”,当你使用一个变量名,比如 double,如果在当前的范围内找不到这个名字,程序就会去全局范围找。如果在全局范围也找不到,就会抛出一个错误,提示 NameError: global name 'double' is not defined

祝你编码愉快。

撰写回答