Dive into Python: HTTP Web Services –
class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):
def http_error_default(self, req, fp, code, msg, headers):
result = urllib2.HTTPError(
req.get_full_url(), code, msg, headers, fp)
result.status = code
return result
HTTPError object initially has no attribute ‘status’, ie. status data attribute does NOT exist in HTTPError class definition. This means when I allocate memory for an instance of HTTPError, no allocation is made for status data attribute.
Then how can I on the fly create a status data attribute for the same instance in the next line? It seems something fascinating is going on beneath that I am unaware of which is giving python this flexibility which was never available in C++/Java
It’s a pity I didn’t catch this until Chapter 11.
Python has a different notion of data types than C or Java. Python does not allocate memory for the data members of an instance if it is created. Instead, when an instance is created, it gets an
__dict__attribute pointing to a dictionary mapping attribute names to values. This dictionary is as dynamic as any standard Python dictionary. If you doan entry with the key
"status"and the valuecodeis added to this dictionary.