NameError: 调用类函数时'getAllElements'未定义

1 投票
2 回答
3035 浏览
提问于 2025-04-17 12:41

我可能忽略了什么,但我有一个叫“parse”的类,里面有一个函数叫“getAllElements”。在主脚本中,我用

from parseXML import parse. 

导入了parse。

然后我执行

parse = parse(file) 

这没问题。但是当我执行

print parseXML.parse(file).getAllElements()

时,我遇到了以下错误:

NameError: global name 'getAllElements' is not defined 

下面是代码。我哪里出错了?

编辑:在评论后修改了代码

class parse:
    # Constructor
    def __init__(self, file):
        # parse the xml file into a tree
        tree = xml.parse('/homes/ndeklein/test.featureXML')
        # Get the root node of the xml file
        self.rootElement = tree.getroot()
        # Set self.parent to rootElement, because the first element won't have a parent (because it is the root)
        self.parent = 'rootElement'
        # dictionary that contains the parent -> child relation
        self.parentChildDict = {}

    # Go recursively through all the elements in the xml file, starting at the choosen rootElement, until only leaves (elements that don't contain elements) are left
    # Return all the elements from the xml file
    def getAllElements(self):
        # if this is the first time this parent is seen:
        #     make elementDict with parent as key and child as value in a list
        if not self.parentChildDict.has_key(self.parent):
            self.parentChildDict[self.parent] = [self.rootElement]
        # else: add the child to the parent dictionary
        else:
            self.parentChildDict[self.parent].append(self.rootElement)
        for node in self.rootElement:
            # if the len of rootElement > 0 (there are more elements in the element):
            #    set self.parent to be node and recursively call getAllElements
            if len(self.rootElement) > 0:
                self.parent = node
                getAllElements()
        return self.parentChildDict

.

#!/usr/bin/env python

# author: ndeklein
# date: 08/02/2012
# function: calls out the script

import parseXML
import xml.etree.cElementTree as xml
import sys

#Parse XML directly from the file path
file = '/homes/ndeklein/EP-B1.featureXML'
# parse the xml file into a tree
print parseXML.parse(file).getAllElements()

2 个回答

1

看起来你在本地找不到 parseXML,因为你用了 from parseXML import parse 这个方式。你有没有试过直接导入 parseXML,然后这样做呢?

import parseXML 
parseXML.parse(file).getAllElements()

你遇到的 NameError 错误是因为你不能直接在方法里调用 getAllElements()。应该用 self.getAllElements() 来调用。

正如评论中提到的,你的代码里还有其他逻辑错误需要修正。

1

这跟你导入的方式和调用的风格有关,正如Praveen提到的。

因为你是这样导入的:

from foo import bar

所以你不需要(实际上也不应该)在调用时明确声明foo。

bar.baz()

不是这样的:

foo.bar.baz()

所以在你的情况下,试试这样调用:

parse(file).getAllElements()

但是你仍然需要处理递归中的裸调用:getAllElements()可能应该改成self.getAllElements()

撰写回答