2013-11-15 41 views
6

這裏是我的example.py文件:NameError:全局名稱 'myExample2' 沒有定義#模塊

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 

我該如何解決這個問題?

+2

你需要'myExample2(self,num)',然後將其稱爲'self.myExample2()' –

回答

6

下面是對您的代碼的簡單修復。

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 
7

我看到了兩個錯誤,在你的代碼:

  1. 你需要調用myExample2self.myExample2(...)
  2. 您需要添加self定義myExample2時:def myExample2(self, num): ...
0

你必須創建一個實例myClass類,而不是整個模塊的實例(我編輯變量名稱不太可怕):

from myimport import * 
def main(): 
    #myobj = myimport.myClass(10) 
    # the next string is similar to above, you can do both ways 
    myobj = myClass(10) 
    myobj.myExample() 

if __name__ == "__main__": 
    main() 
0

而其他的答案是正確的,我不知道是否有真正需要myExample2()是一個方法。你還可實現它的獨立:

def myExample2(num): 
    return num*num 

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

或者,如果你想保持你的命名空間的潔淨,實現它作爲一種方法,但它並不需要self,作爲@staticmethod

def myExample2(num): 
    return num*num 

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

首先,我同意alKid的回答。對於這個問題,這實際上是一個評論,而不是一個答案,但我沒有評論的聲望。

我的評論:

導致該錯誤是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 

我發現這個問題,當我試圖追查一個obs在我自己的代碼中修復「全局名稱未定義」錯誤。由於問題中的錯誤信息不正確,我最終變得更加困惑。當我真正運行代碼並看到實際的錯誤時,這一切都是有道理的。

我希望這可以防止任何人發現此線程有我遇到的同樣的問題。如果比我更有名氣的人想把它變成評論或解決問題,請隨時保留。

+0

對於那些責怪我沒有回答問題的人,我表示抱歉。 ** TLDR:問題中的代碼示例不會產生錯誤。問題無法回答!** – Dennis

相關問題