2016-11-08 2 views
-3
class F: 
    'test' 
    def __init__(self, line, name, file, writef): 
    self.line = line 
    self.name = name 
    self.file = file 

def scan(self): 
    with open("logfile.log") as search: 
     #ignore this part 
     for line in search: 
     line = line.rstrip(); # remove '\n' at end of line 
     if num == line: 
      self.writef = line 

def write(self): 
    #this is the part that is not working 
    self.file = open('out.txt', 'w'); 
    self.file.write('lines to note:'); 
    self.file.close; 
    print('hello world'); 

debug = F; 
debug.write 

아무런 오류없이 실행되지만 여러 가지 방법을 시도하고 온라인으로 검색했지만이 문제가있는 유일한 사람입니다.왜이 간단한 파이썬 프로그램이 작동하지 않습니까?

+3

'F'와 'write'를 잊어 버렸습니다. 'F'와'debug.write'만이 본질적으로 아무런 조작도하지 않습니다. 'self.file.close'도 마찬가지입니다. –

+1

... 당신이'debug.write()'(괄호로 묶음)를하고 싶다는 뜻이다 – Julien

+4

또한 모든 인스턴스 메소드는 클래스 외부에있는 것으로 나타난다 – jonrsharpe

답변

2

들여 쓰기는 파이썬 구문의 일부이므로 일관성을 유지하기위한 습관을 개발해야합니다. 메소드가 클래스 메소드가 될 경우에는 들여 쓰기가 필요합니다.

어쨌든 다음은 수정 된 스크립트 버전입니다.

class F: 
    'test' 
    def __init__(self, line, name, file, writef): 
     self.line = line 
     self.name = name 
     self.file = file 
    def scan(self): 
     with open("logfile.log") as search: 
      #ignore this part 
      for line in search: 
       line = line.rstrip(); # remove '\n' at end of line 
       if num == line: 
        self.writef = line 
    def write(self): 
     # you should try and use 'with' to open files, as if you 
     # hit an error during this part of execution, it will 
     # still close the file 
     with open('out.txt', 'w') as file: 
      file.write('lines to note:'); 
     print('hello world'); 
# you also need to call the class constructor, not just reference 
# the class. (i've put dummy values in for the positional args) 
debug = F('aaa', 'foo', 'file', 'writef'); 
# same goes with the class method 
debug.write() 
관련 문제