简体   繁体   English

将属性添加到列表中的对象python

[英]adding attribute to object in a list, python

I have a file with the attributes for an object on each line. 我有一个文件,其中包含每行上对象的属性。 I want to take the attributes, separated by spaces, and add them to my object. 我想采用以空格分隔的属性,并将它们添加到我的对象中。 I want the objects in a list but I can't get it to work. 我希望列表中的对象,但我不能让它工作。 I have put a comment next to the line that doesn't do what I think it should be able to do. 我已经在不符合我认为应该能够做的事情的线旁边发表评论。 Alternatively if I just pass the words list, 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)

the data is simply 数据很简单

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 am very new to python, and I am finding alot of my ideas for implementing things just don't work so any help would be much appreciated. 我是python的新手,我发现很多我的想法实现的东西只是不起作用所以任何帮助将不胜感激。

Try this: 尝试这个:

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)

Instead of passing each attribute individually, read each line from the file, split it into a list and pass that to the constructor of your Brick object. 不是单独传递每个属性,而是从文件中读取每一行,将其拆分为一个列表并将其传递给Brick对象的构造函数。

You can improve the __init__ method by verifying the content of values before using it. 您可以通过在使用之前验证values的内容来改进__init__方法。

I recommend introducing a function which takes in a string (a line of text in this case) and creates a Brick 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM