我刚刚开始学习Python的课程,我对它们有一个问题。你知道吗
我有一个包含以下行的txt文件:
3 37.5 200
6 36.9 200
9 36.6 100
12 36.6 0
当我运行下面的代码时,它只打印第一行。但是,我想检索所有行。我知道你可以用print()
,但有可能返回吗?你知道吗
class Meds:
def __init__(self, file):
self.file = file
def meds(self):
for i in source.readlines():
data_split = i.strip().split(' ')
hour = data_split[0]
temp = data_split[1]
dose = data_split[2]
return 'At {0}:00 - he had {1} temp, and took {2} mg of meds'.format(hour, temp, dose)
if __name__ == '__main__':
source = open('meds.txt', 'r', encoding='utf8')
a = Meds(source)
print(a.meds())
source.close()
我非常感谢您在这方面的帮助,如果您能提供好的,清晰的源代码来解释Python中的类,我将非常高兴。你知道吗
readlines()
返回文件中的所有行。您想改用readline()
。你知道吗您似乎在迭代
source
,而不是self.file
。从meds()
方法返回时,也只在一行上循环。也可以直接在文件对象上循环。考虑到这一点,循环函数可以如下所示:在调用
meds()
的代码中,可以使用以下命令:要进一步阅读,请参阅文档here。你知道吗
你可以像这样重写你的代码:
在本例中,您将使用生成器generator。你知道吗
你的
Meds
类有两个方法,一个是__init__
,另一个是meds
。你知道吗所以它不是一个类,而是一个伪装的函数。你知道吗
不是每个编程问题都可以而且应该通过编写类来解决。你知道吗
对输入数据运行此操作将返回元组列表:
相关问题 更多 >
编程相关推荐