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.
>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()