从python中的文本文件创建类实例 [英] creating class instances from a text file in python

查看:106
本文介绍了从python中的文本文件创建类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多项式类:

class Polynomial:
    def __init__(self, *termpairs):
        self.termdict = dict(termpairs)

要将实例添加到此类,请输入以下内容:

To add an instance to this class, you enter the following:

P = Polynomial((3,2), (4,5), (9,8))

现在,我正在尝试创建一个从文本文件中读取信息的函数,并从该文本文件中创建Polynomial类的实例.信息存储在文本文件中,如下所示:

Now I'm trying to create a function that reads information from a text file, and from that text file, it creates an instance of the Polynomial class. The information is stored in the text file like this:

4 6
2 3
9 8
3 5
0 42

到目前为止,该函数如下所示:

So far, the function looks like this:

def read_file(polyfilename):
    polyfilename = open("polyfilename.txt", "r")
    poly1 = polyfilename.read()
    polyfilename.close()
    poly1 = [line.split() for line in poly1.split("\n")]
    poly1 = [[int(y) for y in x] for x in poly1]
    for item in poly1:
        return Polynomial(item)

它仅为文本文件中的第一对创建一个多项式实例,如何为文本文件中的所有配对创建一个多项式实例?

It only creates a Polynomial instance for the first pair in the text file, how can I make a Polynomial instance for all of the pairings in the text file?

我现在将其作为功能:

I now have this as my function:

def read_file(polyfilename):
    polyfilename = open("polyfilename.txt", "r")
    poly = polyfilename.read()
    polyfilename.close()
    poly = [line.split() for line in poly.split("\n")]
    poly = [[int(y) for y in x] for x in poly]
    return Polynomial(poly[0], poly[1], poly[2], poly[3], poly[4])

它为我提供了我要找的答案,但是这些文本文件的长度可能会有所不同,因此键入poly [1],poly [2]将不起作用.不管长度是多少,有没有办法我可以遍历每个索引?

It gives me the answer I'm looking for, however, the length of these text files can vary, so typing poly[1], poly[2] won't work. Is there a way I can go through each index no matter what the length is?

推荐答案

您需要的只是

return Polynomial(*poly)

代替

return Polynomial(poly[0], poly[1], poly[2], poly[3], poly[4])

文档此处 ...阅读以"开头的段落语法* expression出现在函数调用""

Docs here ... read the paragraph starting with """If the syntax *expression appears in the function call"""

奖励:您的函数不使用其arg,像疯了一样重用名称poly,并且不是惯用语,因此我重写了整个内容:

Bonus: Your function doesn't use its arg, reuses the name poly like crazy, and isn't idiomatic, so I rewrote the whole thing:

def read_file(polyfilename):
    with open(polyfilename) as f:
        return Polynomial(*[[int(x) for x in line.split()] for line in f])

HTH

这篇关于从python中的文本文件创建类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆