是自我。_ dict __。update(** kwargs)好还是差? [英] Is self.__dict__.update(**kwargs) good or poor style?

查看:863
本文介绍了是自我。_ dict __。update(** kwargs)好还是差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,说我有一些类继承于Shape的类Circle。形状需要x和y坐标,另外,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.)

圆形继承自形状,所以我需要使用命名参数来 __ 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


的界面被记录在案)?

Is this considered a cheat or is this good style (as long as the interface to Circle is well-documented)?

当你有一个简单的,可以理解的代码和头痛代码+很好的docstrings之间的选择,你实际上没有任何选择,你只需去写简单的自我记录的代码:)

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:)

这篇关于是自我。_ dict __。update(** kwargs)好还是差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆