本文介绍了self.__dict__.update(**kwargs) 风格好还是差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,假设我有一个类 Circle,它继承自 Shape.Shape 需要 x 和 y 坐标,此外,Circle 需要一个半径.我希望能够通过执行类似的操作来初始化 Circle,

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 initialize Circle by doing something like,

c = Circle(x=1., y=5., r=3.)

Circle 继承自 shape,所以我需要对 __init__ 使用命名参数,因为不同的类需要不同的构造函数.我可以手动设置 x、y 和 r.

Circle inherits from shape, so I need to use named arguments to __init__, because different classes require different constructors. I could manually set x, y, and r.

class Shape(object):
    def __init__(self, **kwargs):
        self.x = kwargs['x']
        self.y = kwargs['y']

class Circle(Shape):
    def __init__(self, **kwargs):
        super(Circle, self).__init__(**kwargs)
        self.r = kwargs['r']

或者,我可以使用 self.__dict__.update(kwargs)

class Shape(object):
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)

class Circle(Shape):
    def __init__(self, **kwargs):
        super(Circle, self).__init__(**kwargs)

这样做的好处是代码更少,而且我不需要像 self.foo = kwargs['foo'] 那样维护样板文件.缺点是 Circle 需要哪些参数并不明显.这算作弊还是这种风格很好(只要 Circle 的界面有据可查)?

The advantage of this is that there's less code and I don't need to maintain boilerplate like self.foo = kwargs['foo']. The disadvantage is that it isn't obvious which arguments are needed for Circle. Is this considered a cheat or is this good style (as long as the interface to Circle is well-documented)?

感谢大家的深思熟虑的回答.self.__dict__.update(**kwargs) hack 对我尝试组织我的代码很有用,但我会确保我用正确地显式传递参数并清除错误来替换它检查生产代码.

Thanks, everyone, for your thoughtful responses. The self.__dict__.update(**kwargs) hack has been useful for me in experimenting with organizing my code, but I'll make sure that I replace that with properly passing arguments explicitly and doing clear error checking in production code.

推荐答案

class Shape(object):
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

class Circle(Shape):
    def __init__(self, r=None, **kwargs):
        super(Circle, self).__init__(**kwargs)
        self.r = r

就是这样.当你真的不需要它们时,不要使用 **kwargs.

And this is it. Don't use **kwargs when you don't really need them.

这算作弊还是这种风格好(只要Circle 的接口有详细记录)?

当您在编写简单易懂的代码和令人头疼的代码 + 漂亮的文档字符串之间做出选择时,实际上您别无选择,您只需编写简单的、自文档化的代码即可:)

When you have a choice between writing a simple, understandable code and headache code + nice docstrings, you actually don't have any choices, you just go and write simple, self-documented code:)

这篇关于self.__dict__.update(**kwargs) 风格好还是差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 18:11