我正在使用類對象來提高編程技巧。 我有三個文件* .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
謝謝@Martijn,但如果我也有其他功能,我需要導入功能的功能? – 2013-03-01 18:35:24
我添加了一個新的函數「def check_above_threshold」。我是否需要使用核心導入check_below_threshold,check_above_threshold? – 2013-03-01 18:36:57
@Gianni:是的;或導入整個模塊。 'import core'然後使用'core.check_below_threshold(self.z,threshold)'等。 – 2013-03-01 18:38:02