Search code examples
pythonoopstatic-methodsstatic-variables

python class variable in static method


[updated]: Full code

I always get confused with pyhton's staticmethods but according to this (last answer), it should work!

getting error:

AttributeError: class MyConnection has no attribute 'myuser'

class MyConnection:
    def __init__(self, hostname, port, user, password):
        myhostname = hostname
        myport = port
        myuser = user
        mypassword = password
        isisessid = None

    @staticmethod
    def connect():
        my_session = MyConnection()

        headers = {'content-type': 'application/json'}
        headers['Authorization'] = 'Basic ' + string.strip(
            base64.encodestring(MyConnection.myuser + ':' + MyConnection.mypassword))

        body = json.dumps({'username': MyConnection.myuser, 'password': MyConnection.mypassword,
            'services': ['platform', 'namespace']})

        uri = '/session/1/session'

        connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport)
        connection.connect()

        try:
            connection.request('POST', uri, body, headers)
            response = connection.getresponse()
            my_session.isisessid = MyConnection.extract_session_id(
                response.getheaders())
        except Exception, e:
            print e
            connection.close()
        except httplib.BadStatusLine, e:
            print e
            connection.close()

        return my_session

Solution

  • If the attributes are going to be static, don't initialize them in the initializer method, declare them outside at the class level, not at method level.

    But why are you initializing class attributes in the initializer? every instance that you create will overwrite their values!

    I believe you're confusing what instance attributes and class attributes are used for. Why don't you try using only instance attributes? all things considered, having static data is not a good idea. For example:

    class MyConnection:
        def __init__(self, hostname, port, user, password):
            self.myhostname = hostname
            self.myport = port
            self.myuser = user
            self.mypassword = password
        @staticmethod
        def connect():
            my_session = MyConnection()
            print my_session.myuser # just an example