Is self.__dict__.update(**kwargs) good or poor style?

前端 未结 4 873
执笔经年
执笔经年 2020-12-01 04:24

In Python, say I have some class, Circle, that inherits from Shape. Shape needs x- and y-coordinates, and, in addition, Circle needs a radius. I want to be able to initializ

4条回答
  •  北海茫月
    2020-12-01 04:40

    If you wish to assign automatically, I suggest the following approach:

    def __init__(self, **kwargs):
        for key, value in kwargs.iteritems():
            setattr(self, key, value)
    

    which, in terms of style, is somewhere in between writing it explicitly and hacking it yourself using self.__dict__.

提交回复
热议问题