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

前端 未结 4 875
执笔经年
执笔经年 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 05:01

    If you wanted it to be more obvious you could have Circle.__init__ perform some sanity checks on the arguments. Presumably you'd check to make sure all the arguments are there, and possibly raise errors for meaningless arguments.

    You could probably even make a decorator or helper function in Shape to do this for you. Something like this:

    class Circle(Shape):
        def __init__(self, **kwargs):
            self.check(kwargs, 'x', 'y', 'r')
            super(Circle, self).__init__(**kwargs)
    

    .check would be implemented in Shape and essentially just verifies that all the arguments are in kwargs, and possibly that no extra ones are (sorry, no code for that one - you can figure it out on your own). You could even have subclasses overload it to check for optional arguments, which you may want to handle differently than other arguments (i.e. give them a default value that wouldn't otherwise be assigned in Shape.__init__.

    Otherwise, if you document your interface, and it works the way it's documented, it's always alright. Anything else you do to make it work the way we "expect" it to (throwing exceptions for incorrect arguments) is a bonus.

提交回复
热议问题