0

I am building a class that has a number of methods to request different data from the same website. The catch is the session_id needs to stay persistent across all instance methods.

I have written some mock code below and was wondering if this is the correct way to go about it or have I got it all wrong?

import random

class classTest():
    def __init__(self):
        self.session_id = None

    def set_session_id(self):
        if self.session_id == None:
            self.session_id = random.randrange(0,1000)
        return self.session_id

    def use_session_id(self):
        return self.set_session_id()

    def use_session_id_again(self):
        return self.set_session_id()

In the above example I mocked the session_id with a random number and when I test the two different methods I get persistent results, which means it is working great... but is this the correct way to achieve this? Can anyone advise on a better / proper way to do this?

martineau
  • 119,623
  • 25
  • 170
  • 301
Adam Williamson
  • 295
  • 4
  • 12
  • Are you worried about racing condition? – Yu Zhang Mar 27 '19 at 23:02
  • Do you mean that `session_id` has to be the same across all instances, or that each instance should have a persistent `session_id`? – gmds Mar 27 '19 at 23:20
  • You're not setting class attributes, you're setting instance attributes, and yes, that's the way to do that. – martineau Mar 28 '19 at 00:20
  • Thank you for the quick responses. Apologies about the wording, I am new to Python classes. I want the session_id to stay the same within each instance. – Adam Williamson Mar 28 '19 at 00:28
  • Adam: Not too big of a deal...in fact it's a fairly common mistake. One thing a little unusual about Python is that its classes are [first-class objects](https://stackoverflow.com/questions/245192/what-are-first-class-objects) and can be assigned to variables and be passed around just like any other object (and can have their own attributes separate those of any instances of them that get created). A pretty useful feature, IMO. – martineau Mar 28 '19 at 01:00

1 Answers1

2

Tre preferred way is to set session_id only once in __init__ method so after initialization it stays persistent during the whole lifetime of the object. And just not change it after initialization.

Something like this:

import random

class classTest():
    def __init__(self):
        self.session_id = random.randrange(0,1000)

    def use_session_id(self):
        print(self.session_id)

    def use_session_id_again(self):
        print(self.session_id)

test = classTest()  # session_id is set here
test.use_session_id()  # will print session id
test.use_session_id_again()  # will print the same session id
sanyassh
  • 8,100
  • 13
  • 36
  • 70