The AddressBook
class finds uses regex to find a string that matches the pattern, which is a name.
self.contacts
loops through the Contact
class and prints out the pattern in a dictionary format
import re
import sys
class Contact(object):
def __init__(self, match):
for key, value in match.groupdict().items():
setattr(self, key, value)
def __str__(self):
return '\n'.join(
sorted(
["\t{}: {}".format(key, val) for key, val in self.__dict__.items()]))
class AddressBook(object):
def __init__(self, filename):
self.names_file = open(filename, encoding="utf-8")
self.data = self.names_file.read()
self.names_file.close()
line = re.compile('(?P<name>^([A-Z][a-z]*((\s)))+[A-Z][a-z]*$)')
self.contacts = [Contact(match) for match in line.finditer(self.data)]
address_book = AddressBook('contacts.txt')
print (address_book)
This will give me a python object:
<__main__.AddressBook object at 0x0338E410>
But if I add another __str__
method like this...
import re
import sys
class Contact(object):
... #same code as above
class AddressBook(object):
def __init__(self, filename):
self.names_file = open(filename, encoding="utf-8")
self.data = self.names_file.read()
self.names_file.close()
line = re.compile('(?P<name>^([A-Z][a-z]*((\s)))+[A-Z][a-z]*$)')
self.contacts = [Contact(match) for match in line.finditer(self.data)]
def __str__(self):
return '\n'.join('{}'.format(i) for i in self.contacts)
address_book = AddressBook('contacts.txt')
print (address_book)
It actually prints it out:
name: Rick James
name: Charlie Murphy
name: Prince
My question is why does it give me a python object even though I have a __str__
method in the Contact
class?