У меня есть эта функция в 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
Я надеюсь, что приведенный выше код сам объяснительное. Я подозреваю, что есть еще какой-то питонский способ делать то, что я хочу. Любая помощь приветствуется.
Я не уверен, что я следую. Как насчет 'persons = []' и 'persons.append (Person())' (я добавил 's' к имени). Не усложняйте вещи. – keyser
Что-то классное лицо у вас там есть. :) – aIKid
Что означает 'int (100 или 0)' означает? –