2016-11-08 121 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 

它執行沒有錯誤,但什麼都不做,嘗試了很多方法,在網上搜索,但我是唯一一個這個問題。爲什麼這個簡單的python程序不起作用?

+3

您忘記了調用'F'和'write'。只是'F'和'debug.write'實質上不是操作。 'self.file.close'也是如此。 –

+1

......這意味着你想要執行'debug.write()'(帶括號) – Julien

+4

另外,你所有的實例方法都顯示在類之外 – jonrsharpe

回答

2

縮進是python語法的一部分,因此您需要開發一個與之一致的習慣。 對於類方法的方法,他們需要像這樣縮進

無論如何,這是您已經運行的腳本的修改版本,它的工作原理。

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() 
相關問題