使用open()函数时提示AttributeError: 'str' object has no attribute 'filename'
问题相关代码,请勿粘贴截图
gapfilling.py
class Gapfilling:
def __init__(self, filename):
self.filename = filename
def open_file(self):
with open(self.filename, 'r') as file_object:
return file_object
def get_items(self):
lines = Gapfilling.open_file(self.filename).readlines()
return lines
test = Gapfilling('GP_turbine.txt')
x = test.get_items()
print(x)
运行结果及报错内容
Traceback (most recent call last):
File "I:\PythonProgram\QstBankCreating\main.py", line 5, in <module>
x = test.get_items()
File "I:\PythonProgram\QstBankCreating\gapfilling_function.py", line 10, in get_items
lines = Gapfilling.open_file(self.filename).readlines()
File "I:\PythonProgram\QstBankCreating\gapfilling_function.py", line 6, in open_file
with open(self.filename, 'r') as file_object:
AttributeError: 'str' object has no attribute 'filename'
运行后提示:
我的解答思路和尝试过的方法
在类中传递一个字符串失败,实在找不出破的办法,愿解答