2013-03-01 44 views
0

我正在使用類對象來提高編程技巧。 我有三個文件* .py。很抱歉的基本的例子,但是幫助我瞭解在我的錯誤是:使用類 - 解決NameError:全局名稱

/my_work_directory 
    /core.py *# Contains the code to actually do calculations.* 
    /main.py *# Starts the application* 
    /Myclass.py *# Contains the code of class* 

Myclass.py

class Point(object): 
    __slots__= ("x","y","z","data","_intensity",\ 
       "_return_number","_classification") 
    def __init__(self,x,y,z): 
     self.x = float(x) 
     self.y = float(y) 
     self.z = float(z) 
     self.data = [self.x,self.y,self.z] 

    def point_below_threshold(self,threshold): 
     """Check if the z value of a Point is below (True, False otherwise) a 
      low Threshold""" 
     return check_below_threshold(self.z,threshold) 

core.py

def check_below_threshold(value,threshold): 
    below = False 
    if value - threshold < 0: 
     below = not below 
    return below 

def check_above_threshold(value,threshold): 
    above = False 
    if value - threshold > 0: 
     above = not above 
    return above 

當我設置main.py

import os 
os.chdir("~~my_work_directory~~") # where `core.py` and `Myclass.py` are located 

from core import * 
from Myclass import * 

mypoint = Point(1,2,3) 
mypoint.point_below_threshold(5) 

我得到:在其他模塊

Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
    File "Myclass.py", line 75, in point_below_threshold 
    return check_below_threshold(self.z,threshold) 
NameError: global name 'check_below_threshold' is not defined 

回答

1

函數是不是你Myclass模塊中自動顯示。你需要明確導入它們:

from core import check_below_threshold 

或導入core模塊,並使用它作爲一個命名空間:

import core 

# ... 
    return core.check_below_threshold(self.z,threshold) 
+0

謝謝@Martijn,但如果我也有其他功能,我需要導入功能的功能? – 2013-03-01 18:35:24

+0

我添加了一個新的函數「def check_above_threshold」。我是否需要使用核心導入check_below_threshold,check_above_threshold? – 2013-03-01 18:36:57

+0

@Gianni:是的;或導入整個模塊。 'import core'然後使用'core.check_below_threshold(self.z,threshold)'等。 – 2013-03-01 18:38:02

0

你有一個丟失的進口。 你必須在你使用它們的地方導入你的功能。 這意味着,你必須在core.py中導入check_below_threshhold,因爲它在那裏被使用。

相關問題