2013-03-01 104 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,因为它在那里被使用。

相关问题