Background

Classes allow us to define new types for Python. We can first think of a class as defining a new container instead of a list, tuple, set, or dictionary, we can have our own collection of values, each with a chosen name rather than an index/key. We can then read out a value or update a value, much like reading or replacing the values in a list or dictionary. But we can also put methods in a class definition, giving us a way to specify the exact ways we should interact with values of this new type. Once we have created a class definition, we can create as many objects of the new type as we want and use them in our programs. We can create entirely new types during the design phase of writing a program. This enables us to think in terms of types (and instances of types) that better model what we see in the real world, instead of endlessly relying on lists or dictionaries (and having to remember exactly how we intended to use those things as proxies for the values we actually had in mind).

Exceptions allow us to recover from unusual events some unavoidable (user types in bad file name or bad input in general), some unexpected (such as IndexErrors when stepping through a list). Without exceptions, we tend to program in an "ask permission, then attempt" style of calculation. But using exceptions, we can instead program in a "try it first, beg for forgiveness" approach by writing code that specifies how to recover from exceptions that we allowed to occur.

What's Allowed?

As long as you don't import anything, you can use anything built-in or that you create. Now that we're really writing our own datatypes, the built-ins aren't really designed to solve our quite-specific problems! Just as we used to say "add your own helper functions and call them", you can also add your own helper methods and use them.

Task

We will implement some basic classes and method to manage invitations and responses for planning a party. An Event can add/discard Invitations, and can receive Responses. By calling the methods, someone could managd their attendees list for their party.

Notes / Assumptions / Requirements

Don't import anything, and you can use all built-ins/methods that are otherwise available.

adding definitions: You may add additional methods and functions in support of your solution.

displaying things: __str__ and __repr__ are used by many other places in Python to get a string representation of the object. Specifically, str() calls __str__ , and repr() calls __repr__ , on any objects they receive as arguments. __str__ often generates a human-centric representation, appropriate for a human reading what is present. __repr__ often generates a Python-centric representation. The goal of __repr__ is actually to have a string that could be evaluated to re-generate an identical object. In general, we would quite prefer it to look like a valid constructor call, if possible. Ultimately, we can have the same representation in __str__ and __repr__ if we'd like; in fact, when we didn't explicitly describe two different string representations for __str__ and __repr__ to return, we can define one in terms of the other, like this:

def __repr__(self):
return str(self)

Just remember the original intent of __str__ vs __repr__ . It's good practice to define __init__ , __str__ , and __repr__ immediately before writing any extra methods in a Python class at a minimum, and perhaps also __eq__ as well.

what to return? Many methods don't specify a return value, and thus they return None after modifying the object.

handling exceptions: notice where we create exception types, and where we catch those exceptions. Be sure you don't catch the exception too early, or when not requested! When testing smaller parts of your code, it may be possible and even expected/required that specific inputs to a function/method will cause an exception to propagate (crash), rather than returning normally with a return value. We could extend this project to a full program with user interactions; this top-level layer of code would be a great place to catch more exceptions and ask for decisions and responses whenever we catch certain exception types. Since we're not writing the larger program that was described, there's no menu and user interaction present to do this particular style of interaction.

testing individual methods: you can also narrow down the focus of our tester by feeding it the name of a class (which only runs the init/str/repr/eq/lt kinds of tests), or the method name of things that are needed in a particular class; this is the Event class. We had to manually create this listing, and it's how the test cases were named. Here is the full list of test batches you can select:

  • classes: Invitation, Response, InviteNotFoundError, TooManyError, Event
  • methods: find_invite, pop_invite, add_invite, find_response, pop_response, read_response, count_attendees, count_rejections, max_attendance, count_pending, rescind_invitation
  • for example: demo$ python3 tester6p.py Event Response find_invite pop_invite

Required Classes

Working through the classes in the given order is the simplest path to completion. Be sure to complete the init/str/repr/eq/lt definitions before moving on to other classes that use them.

class Invitation:

  • def __init__(self, name, num_invited): create/initialize instance variables for name and num_invited . Assume num_invited is a positive int.
  • def __str__(self): create/return a string as in this example: "Invitation('Alice',2)"
  • def __repr__(self): create/return a string identical to the __str__ output.
  • def __eq__(self, other): determine if this object ( self ) is equivalent to other . Two Invitations are considered equal if they have the same name and same number of invited people.
  • def __lt__(self, other): this is the "less than" method. Return the boolean answer of if self
  • By providing this method, .sort() / sorted() can sort lists of Invitation s.

class Response:

  • def __init__(self, name, ans, num_attending): create/initialize instance variables for all three non- self parameters. Assume ans is a bool and num_attending is a non-negative int.
  • def __str__(self): create/return a string as in this example: "Response('Alice', True, 2)"
  • def __repr__(self): create/return a string identical to the __str__ output.
  • def __eq__(self, other): determine if this object ( self ) is equivalent to other . Two Responses are considered equal if they have the same values for all instance variables.
  • def __lt__(self, other): this is the "less than" method. Return the boolean answer of if self

class InviteNotFoundError(LookupError):

Be sure to include the (LookupError) portion above in your class declaration, so that this is an extension of the LookupError class (with all the exception properties that implies).

  • def __init__(self, name): create/initialize instance variable for name .
  • def __str__(self): create/return a string as in this example: "no invite for 'Alice' found."
  • def __repr__(self): create/return a string as inthis example: "InviteNotFoundError('Alice')"
  • def __eq__(self, other): determine if this object ( self ) is equivalent to other (both have same name ).

class TooManyError(ValueError):

Be sure to include the (ValueError) portion above in your class declaration, so that this is an extension of the ValueError class (with all the exception properties that implies).

  • def __init__(self, num_requested, num_allowed): create/initialize instance variables for both numbers. Assume that num_requested > num_allowed . Assume both are non-negative ints.
  • def __str__(self): create/return a string as in this example: "too many: 4 requested, 3 allowed."
  • def __repr__(self): create/return a string as in this example: "TooManyError(5, 3)"
  • def __eq__(self, other): determine if this object ( self ) is equivalent to other (both have same instance variable values).

class Event:

  • def __init__(self, title, invites=None, responses=None): create/initialize instance variables for title , invites , and responses . When invites or responses is None , use an empty list as the value. The incoming lists of invites and responses might not have been sorted, but must be sorted as part of this constructor.
  • def __str__(self): create/return a string similar to: """Event('party', [], [])"""
    Hint: when obtaining strings for the lists of invites/responses, how can you rely upon other str definitions to make this a short/trivial method to write?
  • def __repr__(self): create/return a string identical to the __str__ output.
  • def __eq__(self, other): determine if this object ( self ) is equivalent to other (both have same instance variable values).
  • find_invite(self, name): retrieve the Invitation by that name, and return a reference to that Invitation object. When no such invitation is found, this method will raise an InviteNotFoundError .
  • pop_invite(self, name): retrieve and remove the invitation by the given name from the list of invites, and return it. Any Response s of the same name should be discarded. When no such invitation is found, this method will raise an InviteNotFoundError .
  • add_invite(self, inv): add this invitation to the event's list of invites; the list must be sorted before returning. If there is already an invitation by that name, discard the previous one. Hint: use sort() .
  • find_response(self, name): retrieve the Response by that name, and return a reference to that Response object. When no such response is found, this method will raise a LookupError such as the following: "no Response found with name='Alice'."
  • pop_response(self, name): retrieve and remove the response by the given name from the list of responses, and return it. When no such response is found, it will raise a LookupError as follows: "no Response found with name='Alice'."
  • read_response(self, response): check the response, and possibly add it to the list of responses, according to the following rules:
    • If the name wasn't on the invitation list, raise an InviteNotFoundError out of the method.
    • When the response indicates more attending than invited, raise a TooManyError out of the method.
    • When the previous two errors are avoided, add response to the list (removing any old ones by that name)
    • The responses list must be sorted before returning.
    • When the response indicates not attending, replace its num_attending with 0 .
  • count_attendees(self): return how many people are currently attending, according to the responses list.
  • count_pending(self): return how many inviteds' invitations have no corresponding response.
  • max_attendance(self): return the highest number of attendees, if all remaining unanswered invitations responded 'yes' with the full number of invited.
  • count_rejections(self): Count how many responses indicated not coming (how many invited people are not coming, not just how many rejection responses were received some are "no" responses, others are bringing less than invited). All responses should have been validated when added, so if a response has no associated invitation, behavior is undefined (you don't have to consider the situation, and whatever your program does in these situations is acceptable; this is the normal idea of "undefined behavior", look for it in specs in the future!).
  • rescind_invitation(self, name): we've decided a person is no longer invited to our party; find and remove the invitation by that name from this event, as well as any response they may have sent. This method raises no errors when invitations or responses weren't found. Hint: use exception handling to make this a simple function.

Example Session

>>> i = Invitation("Alice", 2)
>>> i.__str__()
"Invitation('Alice', 2)"
>>> i.__repr__()
"Invitation('Alice', 2)"
>>> i.__eq__(Invitation("Alice", 2))
True
>>> i.__lt__(Invitation("Bob", 1))
True
>>> i.__lt__(Invitation("Alice", 3))
True
>>> i.__lt__(Invitation("Alex", 3))
False
>>>
>>> r = Response("Alice",True,2)
>>> str(r)
"Response('Alice', True, 2)"
>>> repr(r)
"Response('Alice', True, 2)"
>>> r == Response("Alice",True,2)
True
>>> r == Response("Bob",True,2)
False
>>> r < Response("Bob",True,2)
True
>>> r < Response("Alice",False,2)
False
>>> r < Response("Alice",True,4)
True
>>>
>>> e = Event("party",[Invitation("Alice", 2),
Invitation("Bob", 2), Invitation("Alex", 3)],
[Response("Alice",False,0),
Response("Alex",True,2)])
>>> e
Event('party', [Invitation('Alex', 3),
Invitation('Alice', 2), Invitation('Bob', 2)],
[Response('Alex', True, 2), Response('Alice', False, 0)])
>>> e.find_invite("Alice")
Invitation('Alice', 2)
>>> e.pop_invite("Alice")
Invitation('Alice', 2)
>>> e
Event('party', [Invitation('Alex', 3), Invitation('Bob',
2)], [Response('Alex', True, 2)])
>>> e.add_invite(Invitation("Allen", 3))
>>> e
Event('party', [Invitation('Alex', 3),
Invitation('Allen', 3), Invitation('Bob', 2)],
[Response('Alex', True, 2)])
>>>
>>> e.find_response("Alex")
Response('Alex', True, 2)
>>> e.pop_response("Alex")
Response('Alex', True, 2)
>>> e
Event('party', [Invitation('Alex', 3),
Invitation('Allen', 3), Invitation('Bob', 2)], [])
>>>
>>> e.read_response(Response("Allen",True,2))
>>> e
Event('party', [Invitation('Alex', 3),
Invitation('Allen', 3), Invitation('Bob', 2)],
[Response('Allen', True, 2)])
>>> e.read_response(Response("Alex",False,1))
>>> e
Event('party', [Invitation('Alex', 3),
Invitation('Allen', 3), Invitation('Bob', 2)],
[Response('Alex', False, 0), Response('Allen', True, 2)])
>>> e.count_attendees()
2
>>> e.count_pending()
2
>>> e.max_attendance()
4
>>> e.count_rejections()
4
>>> e.rescind_invitation("Allen")
>>> e
Event('party', [Invitation('Alex', 3), Invitation('Bob',
2)], [Response('Alex', False, 0)])
>>>
>>> # exception related
>>> ie = InviteNotFoundError("Alice")
>>> str(ie)
"no invite for 'Alice' found."
>>> ie == InviteNotFoundError("Bob")
False
>>> raise ie
Traceback (most recent call last):
......
__main__.InviteNotFoundError: no invite for 'Alice'
found.
>>> te = TooManyError(4,3)
>>> str(te)
'too many: 4 requested, 3 allowed.'
>>> te == TooManyError(4,3)
True
>>> raise te
Traceback (most recent call last):
......
__main__.TooManyError: too many: 4 requested, 3 allowed.
>>>
>>> e.find_invite("Patrick")
Traceback (most recent call last):
......__main__.InviteNotFoundError: no invite for
'Patrick' found.
>>> e.pop_invite("Patrick")
Traceback (most recent call last):
......__main__.InviteNotFoundError: no invite for
'Patrick' found.
>>> e.find_response("Patrick")
Traceback (most recent call last):
......
LookupError: no Response found with name='Patrick'.
>>> e.pop_response("Patrick")
Traceback (most recent call last):
......
LookupError: no Response found with name='Patrick'.
>>> e.read_response(Response("Patrick",True,3))
Traceback (most recent call last):
......
__main__.InviteNotFoundError: no invite for 'Patrick'
found.
>>> e.read_response(Response("Bob",True,100))
Traceback (most recent call last):
......
__main__.TooManyError: too many: 100 requested, 2
allowed.
>>> e.rescind_invitation("Patrick")
>>> e
Event('party', [Invitation('Alex', 3), Invitation('Bob',
2)], [Response('Alex', False, 0)])
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.