add object and name in list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: add object and name in list (/thread-38782.html) |
add object and name in list - 3lnyn0 - Nov-23-2022 Hi! How can I add in both list (in first fname and in second the person object) every time when I creat a Person? Secondary how can I add in a list online students? Thanks! class Person: name_persons = [] object_persons = [] def __init__(self, fname, lname, cnp, age): self.fname = fname self.lname = lname self.cnp = cnp self.age = age @staticmethod def add_person(self, fname): self.name_persons.append(fname) def gender(self): if str(self.cnp)[0] == 1: return "m" return 'f' class Student(Person): def __init__(self, nume, prenume, cnp, varsta, medie): super().__init__(nume, prenume, cnp, varsta) self.medie = medi RE: add object and name in list - deanhystad - Nov-24-2022 In the __init__() self.persons.append(self)This saves the Person object which has the name as an attribute. No need for two lists. Actually far better than two lists. Drop the add_person method. gender will always return 'f'. RE: add object and name in list - 3lnyn0 - Nov-24-2022 It works. I would never have thought of that! Thanks! RE: add object and name in list - 3lnyn0 - Nov-24-2022 I'm back with another problem, now I add a person to the list, but if I run the program again, it deletes that person and adds the newly added person. How do I keep the previously added person, should that list be outside the class? RE: add object and name in list - buran - Nov-24-2022 Check Data Persistence and Saving an Object (Data persistence) Of course, you can also store all necessary information e.g. as regular txt/csv or JSON, etc. format and recreate the objects, e.g. https://stackoverflow.com/a/33245595/4046632 |