开发者

What's the pythonic way to set class variables?

perhaps I'm asking the wrong question. I have co开发者_StackOverflow中文版de 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?


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.


You could always do:

self.__dict__.update(locals())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜