python - 方法未定义 - 编译器如何错过它?

标签 python debugging python-3.x compiler-construction error-handling

为什么我的类中的方法在我尝试运行它时编译并说它没有声明的任何线索?任何人都可以在代码中看到,函数 2 在类中声明:

class MyClass():
  def __init__(self):
      pass

  def function2(self,myfilename):
      file = open(myfilename, "r")

      for line in file:
          print(line, end='')

      file.close()

  def function1(self,myfilename):
      function2(myfilename)

def main():
    myfilename = "input.txt"    
    obj = MyClass()
    obj.function1(myfilename) 

if __name__ == '__main__':
    main()

我编译代码没有问题。但是当尝试运行时,它说:

NameError: name 'function2' is not defined

为什么这个编译很好,但是在运行时却崩溃了?有什么建议吗?

最佳答案

替换以下-

  def function1(self,myfilename):
      function2(myfilename)

与-

  def function1(self,myfilename):
      self.function2(myfilename)

关于python - 方法未定义 - 编译器如何错过它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23587448/

相关文章:

python - 关闭 PyQT 窗口后无法杀死它。这需要我重新启动内核

python - 为什么 python 实现使用的内存比 C 多 9 倍?

c++ - 我的 C++ 可执行文件在 Visual Studio 2008 IDE 之外的运行速度比在内部快得多,即使在发行版中也是如此

c++ - 如何在 C++ 中检测/捕获 -1.#IND

python-3.x - 使用自己的图像重新训练对象检测模型( tensorflow )

python - 对字典中的值进行排序 Python 3 - Highscores

python - python 购买主题公园门票程序

python - 嵌套的 python 列表赋值

java - 当调用类的任何方法时中断

从堆栈跟踪中隐藏装饰器的 Python 2 和 3 兼容方法