Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding user to a class
#1
once a class is made how to I add contacts to it in the future with input as apposed to manually inputting the code for example lets say I wanted to add john doe with inputs from a user and store it instead of doing it manually also I want to be able to store a couple so setting john to a variable and grabbing data from that list wouldn't work, also is there a way to keep that stored data if I need to rerun the program I have seen code for address books however the data thats stored in a list is lost once the program is re ran 
 
class Contacts:
    contactCont= 0
    def __init__(self, first_name,last_name, email):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

        Contacts.contactCont +=1
    def display_contact(self):
        print("First Name : ", self.first_name,", Last Name: ",self.last_name, ", Email: ", self.email)

    def name(self):
        n = self.first_name, self.last_name
        return n

    def email(self):
        e = self.email
        return e


john = Contacts("john", "Doe", "[email protected]")
Reply
#2
That is the way that variables works, they are stored in RAM, so you lose all you have done when the program finish. You have no persistence unless you write data into a file or store it into a database.
Reply
#3
where in your computer(s) do you want to keep this data?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Even the simplest address book is a lot of code.  You need a way to enter contacts, remove contacts, find contacts, display contacts.  You also need a way to save your contacts when the program isn't running and load the contacts when the program starts.  Below is the bare minimum.  It is crude, but it should give you some idea of what kind of things you need to do.
class Contact:
    def __init__(self, last_name, first_name, email):
        self.last_name = last_name
        self.first_name = first_name
        self.email = email

    def __str__(self):
        return f'{self.last_name}, {self.first_name} : email={self.email}'

    def __repr__(self):
        return f'{self.last_name},{self.first_name},{self.email}'

    @classmethod
    def read(cls, file):
        info = file.readline().strip().split(',')
        if len(info) == 3:
            return cls(*info)
        return None


class Contacts:
    def __init__(self, db_filename, email):
        self._filename = db_filename
        self._email = email
        self._index = 0
        self._contacts = []

    def __getitem__(self, index):
        return self._contacts[index]

    def __iter__(self):
        self._index = 0
        return self

    def __next__(self):
        if self._index >= len(self):
            raise StopIteration
        self._index += 1
        return self._contacts[self._index-1]

    def __len__(self):
       return len(self._contacts)

    def append(self, last_name, first_name, email=None):
        if email is None:
            email = f'{first_name}.{last_name}@{self._email}'
        self._contacts.append(Contact(last_name, first_name, email))


    def remove(self, last_name, first_name):
        contacts = self.find(last_name, first_name)
        if len(contacts) == 1:
            self._contacts.remove(contacts[0])
            return self
        return None

    def find(self, last_name, first_name=None):
        last_name = last_name.upper()
        contacts = [c for c in self._contacts if c.last_name.upper() == last_name]
        if first_name is not None:
            first_name = first_name.upper()
            contacts - [c for c in contacts if c.first_name.upper() == first_name]
        if len(contacts) > 0:
            return contacts
        return None

    def save(self):
        try:
            with open(self._filename, 'w') as file:
                file.write('\n'.join([c.__repr__() for c in self._contacts]))
        except:
            print(f'Could not save contacts to {self._filename}')

    def load(self):
        try:
            with open(self._filename, 'r') as file:
                while contact := Contact.read(file):
                    self._contacts.append(contact)
        except:
            print(f'Could not read contacts from {self._filename}')


def print_employees(employees, title=None):
    if title is not None:
        underline = '-'*len(title)
        print(f'\n{title}\n{underline}')
    for employee in employees:
        print(employee)


def add_employees(employees):
    while True:
        print_employees(employees, 'Add Employees')
        employee = input('Enter Name (or blank): ').split()
        if len(employee) == 0:
            break;
        mycomp.append(employee[1], employee[0])
        print_employees(mycomp)


def find_employees(employees):
    print('\nFind Employee\n_____________')
    while True:
        employee = input('Enter Name (or blank): ').split()
        if len(employee) == 0:
            break;
        if len(employee) == 1:
            employee.append(None)
        for employee in employees.find(*employee):
            print(employee)
        
def remove_employees(employees):
    while True:
        print_employees(employees, 'Remove Employees')
        employee = input('Enter Name (or blank): ').split()
        if len(employee) == 0:
            break;
        mycomp.append(*employee)


mycomp = Contacts('mycomp_employees.txt', 'mycomp.com')
mycomp.load()

while True:
    cmd = input('\nEnter Command:\n1: List\n2: Hire\n3: Fire\n4: Find\n5: Quit\n? ')
    if len(cmd) < 1:
        break;
    elif cmd[0] == '1':
        print_employees(mycomp, 'MyComp Employees')
    elif cmd[0] == '2':
        add_employees(mycomp)
    elif cmd[0] == '3':
        remove_employees(mycomp)
    elif cmd[0] == '4':
        find_employees(mycomp)
    else:
        break

mycomp.save()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding markers to Folium map only adding last element. tantony 0 2,136 Oct-16-2019, 03:28 PM
Last Post: tantony
  user input to select and print data from another class python TyTheChosenOne 6 4,156 Aug-30-2018, 05:53 PM
Last Post: TyTheChosenOne
  [Help] Using "Class" with User Input in an online sign up form vanicci 8 6,690 Aug-29-2018, 10:52 AM
Last Post: vanicci
  Adding C methods to a pure python class relent95 1 2,931 Nov-03-2017, 03:24 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020