2013-11-17 4 views
0

У меня есть эта функция в Python 3, который работает почти как я хочу работать:Как добавить к новому объекту?

def read_people_from_file(filename): 
    """Function that reads a file and adds them as persons""" 
    print("reading file") 
    try: 
     with open(filename, 'rU') as f: 
      contents = f.readlines() 
    except IOError: 
     print("Error: Can not find file or read data") 
     sys.exit(1) 

    #Remove blank lines 
    new_contents = [] 
    for line in contents: 
     if not line.strip(): 
      continue 
     else: 
      new_contents.append(line) 

    #Remove instructions from file 
    del new_contents[0:3] 

    #Create persons (--> Here is my problem/question! <--) 
    person = 1*[None] 
    person[0] = Person() 
    person[0] = Person("Abraham", "m", 34, 1, 140, 0.9, 90, 0.9, 0.9) 
    for line in new_contents: 
     words = line.split() 
     person.append(Person(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], words[8])) 
    return person 

В последнем фрагменте кода ниже «#create человек», это то, что я не понял, как делать. Как создать пустой список лиц, а затем добавить людей из файла? Если я удалю жестко закодированного человека с именем «Авраам», мой код не работает.

Файл представляет собой текстовый файл с одним человеком в строке с атрибутами, которые появляются после имени.

Часть класса Person выглядит следующим образом:

class Person: 
def __init__(self, name=None, gender=None, age=int(100 or 0), beauty=int(0), intelligence=int(0), humor=int(0), wealth=int(0), sexiness=int(0), education=int(0)): 
    self.name = name 
    self.gender = gender 
    self.age = age 
    self.beauty = beauty 
    self.intelligence = intelligence 
    self.humor = humor 
    self.wealth = wealth 
    self.sexiness = sexiness 
    self.education = education 

Я надеюсь, что приведенный выше код сам объяснительное. Я подозреваю, что есть еще какой-то питонский способ делать то, что я хочу. Любая помощь приветствуется.

+0

Я не уверен, что я следую. Как насчет 'persons = []' и 'persons.append (Person())' (я добавил 's' к имени). Не усложняйте вещи. – keyser

+0

Что-то классное лицо у вас там есть. :) – aIKid

+0

Что означает 'int (100 или 0)' означает? –

ответ

1

Вы можете сделать

persons = [] 
... 
for line in new_contents: 
    words = line.split() 
    persons.append(Person(...)) 
1

Там всегда:

persons = [Person(*line.split()) for line in new_contents] 
0

Это, вероятно, самый простой способ сделать то, что вы хотите:

def readfile(): 
    data = open("file path to read from","r")   #opens file in read mode 
    people = []  
    for line in data:         #goes through each line 
     people.append(Person(*line.split()))    #creates adds "Person" class to a list. The *line.split() breaks the line into a list of words and passes the elements of the list to the __init__ function of the class as different arguments. 
    return people 
Смежные вопросы