[英]What's the pythonic way to set class variables?
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. 而且我发现总是必须要自我x = x。 I know python tries to avoid repetition, so what would be the correct way to do something like this? 我知道python试图避免重复,那么做这样的事情的正确方法是什么?
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')
所以你可以用以下方法删除它: self.__dict__.pop('self')
I don't know how pythonic this approach is, but it works. 我不知道这种方法是如何pythonic,但它的工作原理。
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}
PS:如果你想知道__dict__
是什么,它是一个dict,它以{'member1': value, 'member2': value}
的形式保存一个实例的每个成员
locals()
is a function that returns a dict with local variables. locals()
是一个返回带有局部变量的dict的函数。
你可以随时做:
self.__dict__.update(locals())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.