lundi 29 octobre 2018

Python best practice for object creation

I'm stuck with the best way to create the following object:

I need a dictionary to be returned in the creation of the object. I could have used only one function, but the reality is that with the parameters that are passed in the creation of the object certain operations are performed.

This is the situation:

class Example(object):
    def __init__(self, param_a, param_b, param_c):
        self.a = param_a
        self.b = param_b
        self.c = param_c

        _tmp_1 = self._complex_function_1()
        _tmp_2 = self._complex_function_2()
        _tmp_3 = self._complex_function_3()

        # I need here to return a dictionary. Now I'm saving the 
        # result in a variable call "self.values" and then access to
        # it from the object created, but I don't like this approach...

        def _complex_function_1():
            # Make some calculations using "self"

        def _complex_function_2():
            # Make some calculations using "self"

        def _complex_function_3():
            # Make some calculations using "self"

And when I use it, I have to do the following:

e = Example(a, b, c)

dict_values = e.values

In short: What I want is for Example to return a dictionary. I do not think it's convenient to do it as separate functions because the methods are specific to Example to convert them into functions, and also because they use the parameters of self.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire