名称错误:未定义全局名称“myExample2”模块

2024-04-26 01:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的example.py文件:

from myimport import *
def main():
    myimport2 = myimport(10)
    myimport2.myExample() 

if __name__ == "__main__":
    main()

这里是myimport.py文件:

class myClass:
    def __init__(self, number):
        self.number = number
    def myExample(self):
        result = myExample2(self.number) - self.number
        print(result)
    def myExample2(num):
        return num*num

运行example.py文件时,出现以下错误:

NameError: global name 'myExample2' is not defined

我该怎么解决?


Tags: 文件namefrompyselfnumbermainexample
3条回答

这里有一个简单的代码修复。

from myimport import myClass #import the class you needed

def main():
    myClassInstance = myClass(10) #Create an instance of that class
    myClassInstance.myExample() 

if __name__ == "__main__":
    main()

以及myimport.py

class myClass:
    def __init__(self, number):
        self.number = number
    def myExample(self):
        result = self.myExample2(self.number) - self.number
        print(result)
    def myExample2(self, num): #the instance object is always needed 
        #as the first argument in a class method
        return num*num

首先,我同意阿尔基德的回答。这其实更多的是对问题的评论,而不是回答,但我没有资格发表评论。

我的评论:

导致错误的全局名称是myImport而不是myExample2

说明:

Python 2.7生成的完整错误消息是:

Message File Name   Line    Position    
Traceback               
    <module>    C:\xxx\example.py   7       
    main    C:\xxx\example.py   3       
NameError: global name 'myimport' is not defined

当我试图在自己的代码中找到一个模糊的“global name not defined”错误时,我发现了这个问题。因为问题中的错误信息是不正确的,所以我最终更加困惑。当我实际运行代码并看到实际错误时,一切都是有意义的。

我希望这可以防止任何人发现这个线程有相同的问题,我做了。如果有比我更出名的人想把这个变成一个评论或者解决这个问题,请放心。

我看到你的代码中有两个错误:

  1. 您需要将myExample2调用为self.myExample2(...)
  2. 定义myExample2时需要添加selfdef myExample2(self, num): ...

相关问题 更多 >