I'm making a phonebook and I'm trying to figure out what I'm doing wrong. I have defined a class "people" which should create individual "profiles" for each person that enters in their name and phone-number. Then I have a function that works as the UI for the user. The problem occurs when you try to "lookup" a profile using the name. Python simply tells me that the string object given(the name) doesn't have a "number" attribute.
The code:
class people:
def __init__(self, number):
self.number = number
def main():
while True:
command = str(input(('phoneBook> ')))
segment = command.split()
if segment[0] == 'add':
segment[1] = people(segment[2])
print(segment[1].number)
if segment[0] == 'lookup':
print(segment[1].number)
if segment[0] == 'quit':
pass
Any help is greatly appreciated, and any tips on working with classes or on this specific issue would be great!
Thanks! - TheBigChung
CodePudding user response:
in the 'lookup' part, you are not accessing a people object's number attribute, just accessing the number attribute on a string. one way to do what you want is to keep a dictionary of all people's objects using something as a key(for example their name).
then when you have a 'lookup' query, map the segment[1] the relevant object and return it. also, you can change the attributes of these objects and access them later.