1

I have a class that saves a name, and for each name can record a telephone number and an e-mail address:

class address_book:

    def __init__(self,name):
        self._name=name
        self._info=dict()

    def name(self):
        return self._name

    def add_number(self,number):
        self._info['phone']=number

    def add_email(self,e_mail):
        self._info['email']=e_mail

    def __str__(self):
        return f'Name: {self._name}\nInfo:{self._info}'

First of all I wantto ask you if it is correct, since it is the first class that I write in Python.

Second, I want to ask you if there is any way to print at the same time all the elements that this class contains. For example:

a=address_book('James')
a.add_number(8975436)
a.add_email('James11@xxx')

b=address_book('Carl')
b.add_number(96543436)
b.add_email('carl128@xxx')

c=address_book('Ann')
[...]

If I want to print them all, I have to write:

print(str(a),'\n',str(b),'\n',str(c))

and that's ok since there are just 3 names saved in my address book, but what can I do to see them all at once, when there are many names saved or when I don't know the exact number?

Jenny
  • 259
  • 1
  • 2
  • 12

1 Answers1

1

There's nothing that automatically collects all the instances of a class. You should put them in a list instead of separate variables.

all_addresses = []

a=address_book('James')
a.add_number(8975436)
a.add_email('James11@xxx')
all_addresss.append(a)

b=address_book('Carl')
b.add_number(96543436)
b.add_email('carl128@xxx')
all_addresses.append(b)

...
print(*all_addresses, sep='\n')
Barmar
  • 741,623
  • 53
  • 500
  • 612