python - NameError:调用类函数时未定义全局名称 'getAllElements'

标签 python class instance nameerror

我可能忽略了一些东西,但我得到了一个带有函数“getAllElements”的类“parse”。在主脚本中,我使用

导入解析
from parseXML import 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()

最佳答案

正如 Praveen 提到的,这是你的重要性和通话风格。

因为您以这种方式导入:

from foo import bar

您不需要(实际上不应该)在调用中显式声明 foo。

bar.baz()

不是

foo.bar.baz()

所以在你的情况下尝试调用:

parse(file).getAllElements()

但是您仍然需要解决递归中的裸调用: getAllElements() 可能应该是 self.getAllElements()

关于python - NameError:调用类函数时未定义全局名称 'getAllElements',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9213056/

相关文章:

python - PyQt 代码拆分——设计与功能

ruby - 在 Ruby 中使用面向对象的方法

当所有类实例超出范围时,Java 重置私有(private)静态成员

python - 检查变量是否属于python中的类

python - 如何使用 Shopify Python API RecurringApplicationCharge

python - 从同一目录打开 .txt 文件无法找到该文件(FileNotFoundError) - python/kivy

Python循环遍历Dataframe 'Series'对象没有属性

python - 在 python 中“合并”两个对象

python - 在乒乓球比赛中检测球何时击中 Racket ?

c# - 在使用 “using” block 语句时使用 if else 语句的任何更好的方法?