Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

python - Setting multiple object attributes at once

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?

If I can write

a,b,c=1,2,3

I would like to have something like

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

Having the same effect as

someObject.a=1
someObject.b=2
someObject.c=3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def setattrs(_self, **kwargs):
    for k,v in kwargs.items():
        setattr(_self, k, v)

Use this function like this:

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...