为什么这个简单的python程序不起作用?

时间:2016-11-08 13:14:32

标签: 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):
    #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

它执行时没有任何错误,但没有做任何事情,尝试了很多方法,在网上搜索但是我是唯一一个有这个问题的人。

1 个答案:

答案 0 :(得分: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()
相关问题