Excellent. That was going to be my next question… Great advice! Thanks.
I was riding on the presumption that as long as the instantiation was hard-coded in the Teacher class we could forego error checking, but on second thought, your suggestion is wise. After all, a Student instance can be invoked from anywhere, not just the Teacher class.
Aside: Had to add one more key (‘sid’) to the invalid category check. Works great.
One aspect of the Python track that needs additional material is the object-oriented component. When creating custom types, we should include safeguards for the instantiation process that catch problems before they become runtime errors later on.
Following is another enhanced version of the __init__ method for Student …
def __init__(self, **kwargs):
# check for missing name
if "name" not in kwargs:
raise ValueError("Missing name")
# check for missing sid
if "sid" not in kwargs:
raise ValueError("Missing sid for Student: {:s}".format(kwargs["name"]))
# check for missing grade category
for key in self.criteria:
if key not in kwargs:
raise ValueError("Missing category: {:s} for Student: {:s}".format(key, kwargs["name"]))
# check for invalid named argument
for key in kwargs:
if key not in (list(self.criteria.keys()) + ["name", "sid"]):
raise ValueError("Invalid argument: {:s} for Student: {:s}".format(key, kwargs["name"]))
# check for non-numeric data
for key in self.criteria:
for item in kwargs[key]:
if not isinstance(item, (int, float)):
raise ValueError("Non-numeric item in {:s} for Student: {:s}".format(key, kwargs["name"]))
# arguments are fine; proceed
super(Student, self).__init__()
for key in kwargs:
self[key] = kwargs[key]
… wasn’t sure whether to check for "sid" or "name" first.
EDITED this line in the above on March 20, 2017 …
if key not in (list(self.criteria.keys()) + ["name", "sid"]):
Nice! Appreciate your contribution and guidance. Thanks
sid appears before name, but I’m not sure it matters what order they are checked.
sid is a kind of fudge element since it is arbitrarily inserted in the Teacher class when instantiating a new Student instance. I couldn’t really figure a better way to keep the instances sequential and easy to grab. The roll call is only there as a visual index of id: student.