Is there a reason not to send super().__init__() a dictionary instead of **kwds?

前端 未结 3 818
余生分开走
余生分开走 2021-01-20 05:54

I just started building a text based game yesterday as an exercise in learning Python (I\'m using 3.3). I say \"text based game,\" but I mean more of a MUD than a choose-yo

3条回答
  •  旧巷少年郎
    2021-01-20 06:52

    I've done that myself where in_dict was a dict with lots of keys, or a settings object, or some other "blob" of something with lots of interesting attributes. That's perfectly OK if it makes your code cleaner, particularly if you name it clearly like settings_object or config_dict or similar.

    That shouldn't be the usual case, though. Normally it's better to explicitly pass a small set of individual variables. It makes the code much cleaner and easier to reason about. It's possible that a client could pass in_dict = None by accident and you wouldn't know until some method tried to access it. Suppose Actor.__init__ didn't peel apart in_dict but just stored it like self.settings = in_dict. Sometime later, Actor.method comes along and tries to access it, then boom! Dead process. If you're calling Actor.__init__(var1, var2, ...), then the caller will raise an exception much earlier and provide you with more context about what actually went wrong.

    So yes, by all means: feel free to do that when it's appropriate. Just be aware that it's not appropriate very often, and the desire to do it might be a smell telling you to restructure your code.

提交回复
热议问题