开发者

How is it possible to cook up data attributes for an object on the fly?

开发者 https://www.devze.com 2023-03-24 01:47 出处:网络
Dive into Python: HTTP Web Services - class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler): def http_error_default(self, req, fp, code, msg, headers):

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开发者_JAVA百科 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 do

result.status = code

an entry with the key "status" and the value code is added to this dictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消