Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the pythonic way to set class variables?

Tags:

python

perhaps I'm asking the wrong question. I have 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 redundant to always have to to self.x = x. I know python tries to avoid repetition, so what would be the correct way to do something like this?

like image 638
Scott Avatar asked Mar 02 '26 05:03

Scott


2 Answers

You can avoid doing that 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). So you may remove it with: self.__dict__.pop('self')

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

PS: If you're wondering what __dict__ is, it's a dict that holds every member of an instance in the form {'member1': value, 'member2': value}

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

like image 200
JBernardo Avatar answered Mar 04 '26 18:03

JBernardo


You could always do:

self.__dict__.update(locals())
like image 37
bluepnume Avatar answered Mar 04 '26 19:03

bluepnume



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!