2016-11-08 4 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() 
Смежные вопросы