python类构造函数中是否有’self.somevariable=somevariable’的快捷方式?

Is there a shortcut for `self.somevariable = somevariable` in a Python class constructor?

python中的构造函数通常如下所示:

1
2
3
4
5
class SomeClass:
    def __init__(self, a, b = None, c = defC):
        self.a = a
        self.b = b or []
        self.c = c

是否有这样的快捷方式,例如简单地定义__init__(self,**kwargs)并将键用作self的属性?


一idiom self.__dict__.update(locals())是我见过。如果你运行它right at the beginning of the method,the s this will object'词典更新(因为那些Arguments are with the the only at the beginning of the method .)。如果你在**kwargsYou can do self.__dict__.update(**kwargs)通行证。P></

of this is a当然,脆弱的方法。它可以导致错误的puzzling an argument中如果你accidentally通,masks安现有的属性。如果你为审级,你在.doSomething()method has to the accidentally通doSomething=1构造函数,它会重写the method和安误差原因,以后如果你试图呼叫的方法。for this reason to do this better not是平凡的(除了在一定的案例,如sort of some代理对象只需要谁的目的是作为控股公司的一些属性的"袋")。P></


是的:P></

1
2
3
class SomeClass:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)


有一个问题P></

1
self.__dict__.update(locals())

它包括selfis that self.self,知道你得到。它会是更好的selfout of locals()to filterP></

EG。P></

1
vars(self).update((k,v) for k,v in vars().items() if k != 'self')

你可以用这个方法对accidentally defend overwriting变化P></

1
2
vars(self).update((k,v) for k,v in vars().items()
                   if k != 'self' and k not in vars(self))

如果你不想要它,你可能会silently检查失败,也beforehand like thisP></

1
2
3
if any(k in vars(self) for k in vars()):
    raise blahblah
vars(self).update((k,v) for k,v in vars().items() if k != 'self')