как превратить список строк в объект? - PullRequest
1 голос
/ 27 мая 2019

Это буквально мой второй день на python, поэтому, если это связано со сложными вещами, такими как метаклассы, просто скажите мне, чтобы я мог вернуться к нему, когда стану более опытным.Я пытаюсь преобразовать строки в объекты, и я думаю, что я почти получил, все подробно описано в разделе кода.

mike carpenter miami
jon driver roma
erika student london

# here's my text file, is a list of strings

p = []

with open('people.txt', 'r') as text:
    for line in text:
        values = line.split(' ')
        p.append((values[0], values[1], values[2]))

#this converts each string in the text file in a list of strings with
# substrings becoming strings, all is put in a tuple named p

class person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

#this is my class, pretty self-explanatory
#now I can create objects like this:

person_number_0 = person(p[0][0], p[0][1], p[0][2])

#I can create objects using the tuple, but I don't want to do it manually
#for every different index, so I was thinking about a for-loop

n = 0
for line in p:
    obj = person(p[n][0], p[n][1], p[n][2])
    n = n + 1
#but I don't know how to create a new obj's name for every index


Также, если я запускаю

print(obj.name)

это дает мне Майк, разве это не Эрика, потому что в конце цикла for

obj = person(p[2][0], p[2][1], p[2][2])

или нет?

Если это что-то слишком сложное, я отступлюНе уничтожай меня, пожалуйста.Спасибо всем за любую помощь или уроки.

Ответы [ 2 ]

2 голосов
/ 27 мая 2019

Определив ваш класс таким, какой вы есть, затем просто прочитайте файл как-то так:

with open('people.txt', 'r') as f:
    people = [person(*line.split()) for line in f]

Теперь вы можете видеть содержимое как:

for p in people:
    print(p.name, p.job, p.location)
1 голос
/ 27 мая 2019

Код:

# ignore this part it is the same as your code to read from the file
persons = [x.split() for x in """
    mike carpenter miami
    jon driver roma
    erika student london
""".split('\n')[1:-1]]


class Person:
    # this converts each string in the text file in a list of strings with
    # substrings becoming strings, all is put in a tuple named p
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

    def __str__(self):
        # this allows showing the class as a string (str)
        return "name: {}  job: {}  loc: {}".format(
            self.name, self.job, self.location)


for p in persons:
    print(Person(p[0], p[1], p[2]))

Результаты:

name: mike  job: carpenter  loc: miami
name: jon  job: driver  loc: roma
name: erika  job: student  loc: london
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...