Adding an attribute to an object in a list, python

I have a file with attributes for an object on each line. I want to take whitespace separated attributes and add them to my object. I want objects in a list, but I cannot get it to work. I put a comment next to the line that does not do what I think it should be able to do. Alternatively, if I just pass in a list of words, it stores the entire list in the first attribute of the object.

class Brick(object):
    def __init__(self, xopos=None, yopos=None, xcpos=None, ycpos=None, numb=None, prop=None):
        self.xopos = xopos
        self.yopos = yopos
        self.xcpos = xcpos
        self.ycpos = ycpos
        self.numb = numb
        self.prop = prop

bricklist = []

with open('data.txt', 'r') as f:
    data = f.readlines()

for line in data:
    words = line.split()
    bricklist.append(Brick.xopos(words[0])) #line that doesnt work

for i in range(len(bricklist)):
    print (bricklist[i].xopos)

      

data just

1 13 14 15 16 17
2 21 22 23 24 14
3 3 4 5 6 7
4 1 1 1 1 1
5 5 6 4 1 1 
6 5 6 8 4 2
7 4 9 7 5 6 

      

I'm very new to python and I find a lot of my own ideas for implementing things that just don't work, so any help would be much appreciated.

+3


source to share


2 answers


Try the following:

class Brick(object):
    def __init__(self, values):
        self.xopos = values[0]
        self.yopos = values[1]
        self.xcpos = values[2]
        self.ycpos = values[3]
        self.numb = values[4]
        self.prop = values[5]

bricklist = []

with open('data.txt', 'r') as f:
    for line in f.readlines()
        bricklist.append(Brick(line.split())

for brick in bricklist:
    print (brick.xopos)

      



Rather than passing each attribute separately, read each line from the file, split it into a list, and pass it to Brick's constructor.

You can improve the method __init__

by checking the content values

before using it.

+1


source


I recommend introducing a function that takes in a string (a string of text in this case) and creates an object from it Brick

:



class Brick(object):
    def __init__(self, xopos=None, yopos=None, xcpos=None, ycpos=None, numb=None, prop=None):
        self.xopos = xopos
        self.yopos = yopos
        self.xcpos = xcpos
        self.ycpos = ycpos
        self.numb = numb
        self.prop = prop

    @classmethod
    def from_string(cls, s):
        values = [int(v) for v in s.split()]
        return cls(*values)


with open('data.txt', 'r') as f:
    bricklist = [Brick.from_string(line) for line in f]

      

0


source







All Articles