我正在使用类对象来提高我的编程技巧。 我有三个文件* .py。对于基本示例感到抱歉,但请帮助我了解错误的位置:
/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
答案 0 :(得分:1)
其他模块中的功能在Myclass
模块中不会自动显示。您需要明确导入它们:
from core import check_below_threshold
或导入core
模块并将其用作命名空间:
import core
# ...
return core.check_below_threshold(self.z,threshold)
答案 1 :(得分:0)
您缺少导入。 您必须在使用它们的地方导入功能。 这意味着,您还必须在core.py中导入check_below_threshhold,因为它会在那里使用。