BenH
BenH

Reputation: 720

__str__ method showing None value for a class local variable

I'm having an issue where a class variable is set correctly and displayed correctly inside __init__() when using print, however, trying to display that same variable inside the __str__ method displays None. Three other variables generated the exact same way do not exhibit this behavior.

Here is my code:

class RestRequest(urllib2.Request):
    def __init__(self, host, path, data=""):
        self.host    = host
        self.data    = data
        self.path    = path

        print "RestRequest::init() path: %s" % self.path
        print "RestRequest::init() data: %s" % self.data
        print "RestRequest::init() host: %s" % self.host

        urllib2.Request.__init__(self, self.path)


    def __str__(self):
        return "RestRequest::__str__() host='%s', path='%s', data='%s'" % (self.host, self.path, self.data)

The print statements inside __init__() display the correct values. The value of host inside __str__ is None. The path, method and data variables display correctly inside __str__.

Any ideas?

Upvotes: 0

Views: 104

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122024

urllib2.Request sets self.host = None in __init__. To prevent unexpected things happening, call the superclass __init__ earlier in the subclass __init__:

class RestRequest(urllib2.Request):
    def __init__(self, host, path, data=""):
        urllib2.Request.__init__(self, path) # sets self.host = None
        self.host = host # resets to correct value
        self.path = path
        self.data = data

Upvotes: 1

mgilson
mgilson

Reputation: 309919

You're running into a naming clash with attributes on the super class. You'll need to change the names of your attributes -- or set them after urllib2.Request.__init__ (assuming your values are compatible with what the superclass wants).

Upvotes: 1

Related Questions