0

我正在使用类对象以提高我的编程技能。我有三个文件 *.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
4

2 回答 2

1

其他模块中的功能在您的Myclass模块中不会自动可见。您需要显式导入它们:

from core import check_below_threshold

或导入core模块并将其用作命名空间:

import core

# ...
    return core.check_below_threshold(self.z,threshold)
于 2013-03-01T18:34:13.340 回答
0

您缺少导入。你必须在你使用它们的地方导入你的函数。这意味着,您也必须在 core.py 中导入 check_below_threshhold,因为它在那里被使用。

于 2013-03-01T18:37:08.067 回答