Python Forum

Full Version: add object and name in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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'.
It works. I would never have thought of that! Thanks!
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?
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