lundi 3 août 2020

@setter: Pass and set all class properties in one method

I have a need for a Singleton class instance that is accessible from anywhere has certain session variables that can change.

class MySingletonClass(Singleton):

    @property
    def session(self):
        return self

    @session.setter
    def session(self, d):
        self.name = d['name']
        self.id = d['id']
        self.mode = d['mode']

experiment = MySingletonClass()

This can then be imported and variables set as such

from core import experiment
experiment.session={'name':'my_exp_name', 'mode':'my_mode', 'id':"1234"}

I want to pass them all in one but instead of a dictionary as I have currently, as a function argument. So something like the following:

experiment.set_session('my_exp_name', 'my_mode','1234')

My current property approach prevents that from doing. I do want to maintain each session variable as a property in and of itself but I also want to set them all together since there are plenty of session variables. Just dont like the passing it as a dictionary.

I would appreciate if someone can help with the design and/or make it better. I need an instance of a class that has a bunch of variables that can be accessed from anywhere. The variables inside the class can change but not the class instance itself. And I need a better was to set all the variables in one go (preferably a method instead of setting the dictionary)

Aucun commentaire:

Enregistrer un commentaire