[英]Create object with variable attributes in a cleaner way in python
Am new to python and I had to create an object only with certain attributes that are not None
. 我是python的新手,我只需要创建一个具有非
None
属性的对象。 Example: 例:
if self.obj_one is None and self.obj_two is None:
return MyObj(name=name)
elif self.obj_one is not None and self.obj_two is None:
return MyObj(name=name, obj_one=self.obj_one)
elif self.obj_one is None and self.obj_two is not None:
return MyObj(name=name, obj_two=self.obj_two)
else:
return MyObj(name=name, obj_one=self.obj_one, obj_two=self.obj_two)
Coming from a Java land I know python is full of short hand so wanted to know if there is a cleaner way for writing the above? 我来自Java领域,我知道python简直是空手,所以想知道是否有更干净的方法编写上述代码? Of course my actual object has plenty more attributes.
当然,我的实际对象具有更多的属性。 I tried searching but couldn't find anything helpful so am in doubt if its possible or not cause this doesn't scale if there are more than 2 variable attributes.
我尝试搜索,但找不到任何有用的信息,因此,如果变量属性超过2个,是否有可能导致此问题无法解决,我对此表示怀疑。
One way could be using the double-star operator , like this: 一种方法是使用双星运算符 ,如下所示:
kwargs = {'name': name}
if self.obj_one is not None:
kwargs['obj_one'] = self.obj_one
if self.obj_two is not None:
kwargs['obj_two'] = self.obj_two
return MyObj(**kwargs)
In plain words: you construct a dictionary with your keyword arguments, and then pass that dictionary preceded by **
to the callable. 用简单的话来说:您用关键字参数构造一个字典,然后将该字典前面带
**
传递给可调用对象。
However, None
is often (not always) used as a default value for optional arguments. 但是, 通常 (并非总是)将
None
用作可选参数的默认值。 Probably this will work too: 也许这也可以工作:
return MyObj(name=name, obj_one=self.obj_one, obj_two=self.obj_two)
without any if
or that sort of stuff. 没有任何
if
或那样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.