Skip to content Skip to sidebar Skip to footer

Creating Class Instances From A Text File In Python

I have a polynomial class: class Polynomial: def __init__(self, *termpairs): self.termdict = dict(termpairs) To add an instance to this class, you enter the following:

Solution 1:

All you need is

return Polynomial(*poly)

instead of

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

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

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

defread_file(polyfilename):
    withopen(polyfilename) as f:
        return Polynomial(*[[int(x) for x in line.split()] for line in f])

HTH

Solution 2:

return always exits the function immediately upon calling and can only return one item. So if you want multiple items (in a sense) to be returned, you must pack them in a list, then return that.

In place of the for loop:

polys = []
for item in poly1:
    polys.append(Polynomial(item))
return polys

You will of course have to deal with this new result as a list.

Solution 3:

At a quick glance, it looks like this is returning after the first one is created, so you only get one back. Try replace the return statement with a yield then:

for p inread_file('somefile'):
  # p is a polynomial object, do what you will with it

In case it helps the first response here is a good summary of yield. Again this is just from a quick look at what you've written.

    def read_file(polyfilename):
        polyfilename = open(polyfilename, "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:
            yield Polynomial(item)

    for p in read_file('sample.txt'):
        print p

Produces

<__main__.Polynomialinstanceat0x39f3f0><__main__.Polynomialinstanceat0x39f418><__main__.Polynomialinstanceat0x39f3f0><__main__.Polynomialinstanceat0x39f418><__main__.Polynomialinstanceat0x39f3f0>

Post a Comment for "Creating Class Instances From A Text File In Python"