T-bone's House
T-bone's House

Reputation: 25

Should a dict that I use only once during initialization be put inside my class?

I only need to use operatorDict one time to determine which operation I am using for the class. What is the most pythonic way to store the correct operator inside of self._f ?

class m:
    def __init__(self,n,operator,digit1,digit2):
        self._operatorDict = {'+':add, '-':sub, 'x':mul, '/':truediv}
        self._f = self._operatorDict[operator]
        self._score = 0
        self._range = n
        self._aMin, self._aMax = getMaxMinDigits(digit1)
        self._bMin, self._bMax = getMaxMinDigits(digit2)

Upvotes: 1

Views: 42

Answers (1)

mgilson
mgilson

Reputation: 310227

Much of this depends on how much of the operatorDict you want to expose. In this case, I'd probably recommend one of two things.

Option 1: Put the dict on the class:

class m:
    _operatorDict = {'+':add, '-':sub, 'x':mul, '/':truediv}

    def __init__(self,n,operator,digit1,digit2):
        self._f = self._operatorDict[operator]
        self._score = 0
        self._range = n
        self._aMin, self._aMax = getMaxMinDigits(digit1)
        self._bMin, self._bMax = getMaxMinDigits(digit2)

Since the _operatorDict isn't going to mutate inside the class, it doesn't really seem necessary to have it as a instance attribute. However, it still belongs to the class in some sense. This approach also allows you to change the operatorDict as necessary (e.g. in a subclass).

Option 2: Put the dict in the global namespace:

_operatorDict = {'+':add, '-':sub, 'x':mul, '/':truediv}

class m:

    def __init__(self,n,operator,digit1,digit2):
        self._f = _operatorDict[operator]
        self._score = 0
        self._range = n
        self._aMin, self._aMax = getMaxMinDigits(digit1)
        self._bMin, self._bMax = getMaxMinDigits(digit2)

The advantages here are similar to before -- mainly that you only create one operatorDict and not one per instance of m. It's also a little more rigid in that this form doesn't really allow for easy changing of the operatorDict via subclassing. In some cases, this rigidity can be desirable. Also, as some noted in the comments, if you use this second option, naming _operatorDict to indicate that it is a constant in your naming system (e.g. _OPERATOR_DICT in pep8) is probably a good idea.

Upvotes: 2

Related Questions