Python equivalent to VB “with” block

前端 未结 4 423
北海茫月
北海茫月 2020-12-22 08:46

VB (and C99 and C#, actually) have a way to set multiple attributes on one object with a contracted syntax where you don\'t have to repeat the object name before \".\" . Is

4条回答
  •  渐次进展
    2020-12-22 09:33

    Let's write a function!

    def update_attr(obj, **kw):
        for key, value in kw.iteritems():
            setattr(obj, key, value)
    

    Let's use the function!

    class X:
        pass
    
    x = X()
    
    update_attr(x, blue=3, red=5)
    update_attr(x, **{'yellow': 6})
    
    print vars(x)
    

    The output!

    {'blue': 3, 'yellow': 6, 'red': 5}
    

提交回复
热议问题