PYTHON just the setattr 2. (5 pts) Complete the class History, which should (a)
ID: 3602616 • Letter: P
Question
PYTHON
just the setattr
2. (5 pts) Complete the class History, which should (a) use a dictionary (hint: I used defaultdict) to remember a complete history of all the values binding to all the attribute names, (b) be able to retrieve the current and previous values of an attribute (by appending any number of_prev suffixes for the attribute's name; each_prev goes back to an earlier value), (c) be able to retrieve a dictionary of the current and historical binding using indexing (0 means current values, -1 means previous value, -2 means previous to previous values, etc). The class is initialized with no arguments (it creates a dictionary with no items). 1. Write the_setattr_method to (a) disallow any new attributes containing the string '_prev' raise a NameBrror with an appropriate string describing the problem/values; (b) update both the dictionary of historical values and current values (in self._dict__) with the new value for an attribute name (except for the name you use to store the historical dictionary itself). See the lecture notes. Hint: My method body has 7 linesExplanation / Answer
Hi,
The __setattr__ function can be coded this way:
__setattr__(self,name,value):
if name in self.__dict__:
self.__dict__[name]= value
elif name not in self.__dict__:
if '_prev' in name:
try:
raise NameError("This attribute name contains _prev and so not allowed")
except NameError:
print('This is a NameError Exception!")
raise
else:
self.__dict__[name]= value
Thanks,
Hema.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.