为什么这个简单的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
它执行没有错误,但什么都不做,尝试了很多方法,在网上搜索,但我是唯一一个这个问题。为什么这个简单的python程序不起作用?
答
缩进是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()
您忘记了调用'F'和'write'。只是'F'和'debug.write'实质上不是操作。 'self.file.close'也是如此。 –
......这意味着你想要执行'debug.write()'(带括号) – Julien
另外,你所有的实例方法都显示在类之外 – jonrsharpe