What is the pythonic way to set class variables?

Perhaps I am asking the wrong question. I have a code like this:

class ExpressionGrammar(Grammar):
  def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
    self.nonterminals = nonterminals
    self.terminals = terminals
    self.rules = rules
    self.macros = macros
    self.precedence = precedence
    self.nonterminal = nonterminal

and I find it unnecessary to always have the value self.x = x. I know python is trying to avoid repetition, so what would be the right way to do something like this?

+3
source share
2 answers

You can avoid this with something like:

class C(object):
    def __init__(self, x, y, z, etc):
        self.__dict__.update(locals())

then all these arguments become members (including the self argument). Therefore, you can remove it with:self.__dict__.pop('self')

I don't know how pythonic this approach is, but it works.

PS: If you are interested in what it is __dict__, then this is a dict that contains each instance element in the form{'member1': value, 'member2': value}

locals() is a function that returns a dict with local variables.

+9
source

:

self.__dict__.update(locals())
+1

All Articles