Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with referring to methods in classes in python

i have this code:

class Contact:
    def __init__(self, name, phone):
        Contact.name = name
        Contact.phone = phone
class AddContact:
    def __init__(self):
        self.People = []
    def add_people(self, x):
       self.People.append(x)
    def print_contact(self):
        for x in self.People:
            print("name:" + x.name)
            print("phone:", x.phone)

while True:
    print("----MENU----")
    print("1 -> add contact")
    print("2 -> contact list")
    choice = int(input("enter your choice: "))
    if choice == 1:
        name = input("enter the name of the contact: ")
        phone = input("enter the phone number of the contact: ")
        person = Contact(name, phone)
        AddContact.add_people(person)
    if choice == 2:
        AddContact.print_contact()

what im trying to make is a contact book where the user can add and view all of his contacts, ive recently learned classes and thought this was the correct way to make it but i get issues the erros im getting is that the parameters x and self are unfilled on this line:

def add_people(self, x):

when i call them below outside of the class, ive been trying but i dont understand the problem and would like some assistance.
thanks is advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using AddContact wrong. You need to create an instance of it (just like you created an instance of Contact).

While we are at it, PhoneBook would be a much better name for this class.

...
class PhoneBook:
    def __init__(self):
        self.People = []

    def add_people(self, x):
       self.People.append(x)

    def print_contact(self):
        for x in self.People:
            print("name:" + x.name)
            print("phone:", x.phone)


phone_book = PhoneBook()

while True:
    print("----MENU----")
    print("1 -> add contact")
    print("2 -> contact list")
    
    choice = int(input("enter your choice: "))
    
    if choice == 1:
        name = input("enter the name of the contact: ")
        phone = input("enter the phone number of the contact: ")
        person = Contact(name, phone)
        phone_book.add_people(person)

    if choice == 2:
        phone_book.print_contact()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading