如何解决“self”上的导入错误Python 中没有全局定义?

发布于 2024-12-14 16:09:14 字数 3506 浏览 1 评论 0原文

所以我不断收到这个错误,当我谷歌搜索它时,最常见的修复方法是确保类的所有方法都将“self”作为第一个参数。这是错误:

<代码> 文件“C:\Users\me\Documents\Project\code\model\TrainEvent.py”,第 9 行,位于 NameError: 全局名称“self”未定义按任意键继续。 。 。

这似乎是一个常见错误,只需简单修复即可,但我的所有方法都将 self 作为第一个参数。然后我意识到回溯只是指向声明类名的行。它没有指向我用 self 调用方法的行。这个错误早在这之前就已经被提出了。事实上,它似乎是在导入时提出的。这是 TrainEvent.py。

    from xml.etree.ElementTree import Element

    class TrainEvent(object):

        def __init__(self, element):
            self._element = element
            self.MsgId = self.__tagGrab('MsgId')
            self.MsgTime = self.__tagGrab('MsgTime')
            self.Offset = self.__tagGrab('Offset')
            self.TranId = self.__tagGrab('TranId')
            self.Portal = self.__tagGrab('Portal')
            moveElem = self._element.find('Move')
            self.StartTime = self.__tagGrab('StartTime', moveElem)
            self.EndTime = self.__tagGrab('EndTime', moveElem)
            self.Type = self.__tagGrab('Type', moveElem)
            carElem = self._element.find('Car')
            self.Name = self.__tagGrab('Name', carElem)
            self.UniqueId = self.__tagGrab('UniqueId', carElem)
            self.Orientation = self.__tagGrab('Orientation', carElem)
            self.Wells = self.__tagGrab('Wells', carElem)
            self.Axles = self.__tagGrab('Axles', carElem)
            self.Length = self.__tagGrab('Length', carElem)
            self.IsEngine = self.__tagGrab('IsEngine', carElem)
            self.IsGhost = self.__tagGrab('IsGhost', carElem)

        def getTree(self):
            aTree = Element('ApsMessage')
            self.__addTag(aTree, 'MsgId', self.MsgId)
            self.__addTag(aTree, 'MsgTime', self.MsgTime)
            self.__addTag(aTree, 'Offset', self.Offset)
            self.__addTag(aTree, 'TranId', self.TranId)
            self.__addTag(aTree, 'Portal', self.Portal)
            moveElem = Element('Move')
            self.__addTag(moveElem, 'StartTime', self.StartTime)
            self.__addTag(moveElem, 'EndTime', self.EndTime)
            self.__addTag(moveElem, 'Type', self.Type)
            aTree.append(moveElem)
            carElem = Element('Car')
            self.__addTag(carElem, 'Name', self.Name)
            self.__addTag(carElem, 'UniqueId', self.UniqueId)
            self.__addTag(carElem, 'Orientation', self.Orientation)
            self.__addTag(carElem, 'Wells', self.Wells)
            self.__addTag(carElem, 'Axles', self.Axles)
            self.__addTag(carElem, 'Length', self.Length)
            self.__addTag(carElem, 'IsEngine', self.IsEngine)
            self.__addTag(carElem, 'IsGhost', self.IsGhost)
            aTree.append(carElem)
            return aTree

        def getTag(self):
            return self._element.tag

        def __tagGrab(self, tagName, parent=self._element):
            '''
            Helper function for XML reading operations.
            '''
            return parent.find(tagName).text


        def __addTag(self, element, tagName, textValue=None):
            '''
            Helper function for setting values for XML elements. Note that this
            function assumes unique tag name values within element.
            '''
            element.append(Element(tagName))
            if textValue:
                element.find(tagName).text = str(textValue)

因此,如果我所有的方法都将 self 作为第一个参数,并且调用堆栈指向类声明作为问题,但 self 没有在全局范围内定义,那么我在这里做错了什么?

PS:如果有帮助的话,我正在使用最新的 IronPython 解释器,以防由于某种原因问题是 IronPython 特有的。

So I keep getting this error that when I Google for it, the most common fix for it is to be sure that all the methods of a class have 'self' as the first argument. Here is the error:


File "C:\Users\me\Documents\Project\code\model\TrainEvent.py", line 9, in
NameError: global name 'self' is not definedPress any key to continue . . .

This seems like a common error with a simple fix except all my methods do have self as the first argument. Then I realized the traceback is simply pointing at the line where the class name is declared. It is not pointing at a line where I call a method with self. This error is being raised long before that. In fact, it seems to be raised upon importing. Here is TrainEvent.py.

    from xml.etree.ElementTree import Element

    class TrainEvent(object):

        def __init__(self, element):
            self._element = element
            self.MsgId = self.__tagGrab('MsgId')
            self.MsgTime = self.__tagGrab('MsgTime')
            self.Offset = self.__tagGrab('Offset')
            self.TranId = self.__tagGrab('TranId')
            self.Portal = self.__tagGrab('Portal')
            moveElem = self._element.find('Move')
            self.StartTime = self.__tagGrab('StartTime', moveElem)
            self.EndTime = self.__tagGrab('EndTime', moveElem)
            self.Type = self.__tagGrab('Type', moveElem)
            carElem = self._element.find('Car')
            self.Name = self.__tagGrab('Name', carElem)
            self.UniqueId = self.__tagGrab('UniqueId', carElem)
            self.Orientation = self.__tagGrab('Orientation', carElem)
            self.Wells = self.__tagGrab('Wells', carElem)
            self.Axles = self.__tagGrab('Axles', carElem)
            self.Length = self.__tagGrab('Length', carElem)
            self.IsEngine = self.__tagGrab('IsEngine', carElem)
            self.IsGhost = self.__tagGrab('IsGhost', carElem)

        def getTree(self):
            aTree = Element('ApsMessage')
            self.__addTag(aTree, 'MsgId', self.MsgId)
            self.__addTag(aTree, 'MsgTime', self.MsgTime)
            self.__addTag(aTree, 'Offset', self.Offset)
            self.__addTag(aTree, 'TranId', self.TranId)
            self.__addTag(aTree, 'Portal', self.Portal)
            moveElem = Element('Move')
            self.__addTag(moveElem, 'StartTime', self.StartTime)
            self.__addTag(moveElem, 'EndTime', self.EndTime)
            self.__addTag(moveElem, 'Type', self.Type)
            aTree.append(moveElem)
            carElem = Element('Car')
            self.__addTag(carElem, 'Name', self.Name)
            self.__addTag(carElem, 'UniqueId', self.UniqueId)
            self.__addTag(carElem, 'Orientation', self.Orientation)
            self.__addTag(carElem, 'Wells', self.Wells)
            self.__addTag(carElem, 'Axles', self.Axles)
            self.__addTag(carElem, 'Length', self.Length)
            self.__addTag(carElem, 'IsEngine', self.IsEngine)
            self.__addTag(carElem, 'IsGhost', self.IsGhost)
            aTree.append(carElem)
            return aTree

        def getTag(self):
            return self._element.tag

        def __tagGrab(self, tagName, parent=self._element):
            '''
            Helper function for XML reading operations.
            '''
            return parent.find(tagName).text


        def __addTag(self, element, tagName, textValue=None):
            '''
            Helper function for setting values for XML elements. Note that this
            function assumes unique tag name values within element.
            '''
            element.append(Element(tagName))
            if textValue:
                element.find(tagName).text = str(textValue)

So if all my methods have self for a first argument and the call stack was pointing at the class declaration as the problem, but for self not being defined globally, then what did I do wrong here?

PS: If it helps at all, I am using the latest IronPython interpreter in case the problem is IronPython specific for some reason.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

り繁华旳梦境 2024-12-21 16:09:16

问题出在您的 __tagGrab 函数中:

def __tagGrab(self, tagName, parent=self._element):

您不能在标头中包含 self - 而是在正文中包含 None 然后更正:

def __tagGrab(self, tagName, parent=None):
    if parent is None:
        parent = self._element
    ...

原因是在创建类对象时没有 self;除了 globals() (它有 Element 以及其他一些项目)之外,当 Python 到达 __tagGrab 时定义的唯一名称是 __module____init__getTreegetTag

作为向自己证明这一点的实验,请尝试以下操作:

class TestClassCreation(object):
    print("Started creating class")
    print("names so far: %s" % vars())

    def __init__(self):
        pass
    print("now we have %s" % vars())

    def noop(self, default=None):
        print("this gets run when noop is called")
    print("and now have %s" % vars())
    print()

    print("and now we'll fail...")
    def failure(self, some_arg=self.noop):
        pass
    print("we never get here...")

The problem is in your __tagGrab function:

def __tagGrab(self, tagName, parent=self._element):

You cannot have self in the header -- rather have None and then correct in the body:

def __tagGrab(self, tagName, parent=None):
    if parent is None:
        parent = self._element
    ...

The reason is that when the class object is being created there is no self; besides globals() (which has Element plus a couple other items), the only names defined when Python gets to __tagGrab are __module__, __init__, getTree, and getTag.

As an experiment to prove this to yourself, try this:

class TestClassCreation(object):
    print("Started creating class")
    print("names so far: %s" % vars())

    def __init__(self):
        pass
    print("now we have %s" % vars())

    def noop(self, default=None):
        print("this gets run when noop is called")
    print("and now have %s" % vars())
    print()

    print("and now we'll fail...")
    def failure(self, some_arg=self.noop):
        pass
    print("we never get here...")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文