假设有一个带有构造函数(或其他函数)的类,该类带有可变数量的参数,然后将它们有条件地设置为类属性。如何在python中设置可变参数(kwargs)的类属性
我可以手动设置它们,但似乎变量参数在python中已经足够普遍,应该有一个常见的习惯用法。但我不知道如何动态地做到这一点。
我有一个使用eval的例子,但这不是安全的。我想知道正确的方法来做到这一点 - 也许与lambda?
class Foo:
def setAllManually(self, a=None, b=None, c=None):
if a!=None:
self.a = a
if b!=None:
self.b = b
if c!=None:
self.c = c
def setAllWithEval(self, **kwargs):
for key in **kwargs:
if kwargs[param] != None
eval("self." + key + "=" + kwargs[param])
它看起来像这些问题是相似的:http://stackoverflow.com/questions/3884612/automatically-setting-class-member-在python中的变量http://stackoverflow.com/questions/356718/how-to-handle-constructors-or-methods-with-a-different-set-or-type-of-argument http:// stackoverflow。 com/questions/1446555/python-decorator-to-ensure-that-kwargs-are-correct,因此它看起来像我想要的可能是this-- self .__ dict __ [key] = kwargs [key] – fijiaaron
与你无关问题,但你可能想检查[PEP8](http://www.python.org/dev/peps/pep-0008/)关于传统Python样式的一些提示。 –
这里有一个很棒的图书馆,叫做attrs。只需'pip install attrs',用'@ attr.s'装饰你的类,并设置参数为'a = attr.ib(); b = attr.ib()'等。阅读更多[这里](https://glyph.twistedmatrix.com/2016/08/attrs.html)。 –