Domanda

Any clues why the method in my class compiles and says that it was not declared when after I try to run it? As anyone can see in the code, the function2 is declared in the class:

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()

I compile the code with no problem. But when trying run, it says:

NameError: name 'function2' is not defined

Why this compiles nicely, but though get crashed when put to run? Any suggestions?

È stato utile?

Soluzione

Replace the following -

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

with -

  def function1(self,myfilename):
      self.function2(myfilename)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top