一次设置多个对象属性 [英] Setting multiple object attributes at once

查看:74
本文介绍了一次设置多个对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在同一行上设置同一对象的多个属性,类似于将值分配给多个变量的方法?

Is there a way to set multiple attributes of the same object on a single line, similarly to the way one assigns values to multiple variables?

如果我能写

a,b,c=1,2,3

我想要类似的东西

someObject.(a,b,c)=1,2,3

具有与

someObject.a=1
someObject.b=2
someObject.c=3

推荐答案

def setattrs(_self, **kwargs):
    for k,v in kwargs.items():
        setattr(_self, k, v)

像这样使用此功能:

setattrs(obj,
    a = 1,
    b = 2,
    #...
)

您也可以在类上定义此函数,但这将不太通用(即仅适用于该类实例).

You can also define this function on class, but that would be less generic (i.e. apply only to that class instances).

另一个答案提到了__dict__.update,可以将其重写以消除引号:obj.__dict__.update(a=1, b=2),但是我不建议使用此方法:它不适用于属性,并且如果迁移,可能很难注意到从简单的属性到属性.基本上,__dict__是隐藏的"属性,实现细节,除非您真的想以某种方式更改实现,否则不应该使用它.

Another answer mentions __dict__.update and it can be rewritten to get rid of quotes: obj.__dict__.update(a=1, b=2), however i would not recommend using this method: it doesn't work with properties and it might be hard to notice if you migrate from simple attributes to properties. Basically, __dict__ is "hidden" attribute, implementation detail, which you shouldn't use unless you really want to change implementation in some way.

这篇关于一次设置多个对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆