kwargs 解析最佳实践
有没有更紧凑/有效的方法来做到这一点?
for key in kwargs:
if key == 'log':
self.log = kwargs[key]
elif key == 'bin':
self.bin = kwargs[key]
elif key == 'pid':
self.pid = kwargs[key]
elif key == 'conf':
self.conf = kwargs[key]
Is there a more compact/efficient way of doing this?
for key in kwargs:
if key == 'log':
self.log = kwargs[key]
elif key == 'bin':
self.bin = kwargs[key]
elif key == 'pid':
self.pid = kwargs[key]
elif key == 'conf':
self.conf = kwargs[key]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
要准确实现您的要求,您可以使用
or
但是,我通常更喜欢这样的东西:
虽然这仍然有些重复,但代码确实很容易阅读。无论是否传入相应的关键字参数,所有属性都会被初始化,并且函数的签名清楚地记录了参数和默认值。
To achieve exactly what you asked for, you could use
or
However, I would generally prefer something like this:
While this is still somewhat repetitive, the code is really easy to read. All attributes are intialized regardles of whether the corresponding keyword argument is passed in, and the signature of the function clearly documents the arguments and there defaults.
这还有一个额外的优点,即在任何情况下都会分配
self.log
(AttributeError
意味着您的代码已经严重损坏,仅此而已。始终确保所有内容都已分配。) 。没有额外的self.log = default_log
行。您可以省略默认值以获得None
。This has the additional advantage that
self.log
is assigned in any case (AttributeError
means your code is broken as hell, nothing more. Always make sure everything is always assigned.). Without extraself.log = default_log
lines. You can omit the default to getNone
.如果
get()
中提供的键不在字典中,则结果为None
。If the key provided in
get()
is not in the dictionary the result isNone
.其中
setattr(self, "bin", "val")
就像调用self.bin = "val"
但是更希望有一个像 @Sven 这样的白名单马尔纳克有。
In which
setattr(self, "bin", "val")
is like callingself.bin = "val"
However it is more desirable to have a whitelist like @Sven Marnach has.
self.__dict__.update(kwargs)
self.__dict__.update(kwargs)
我的解决方案是:
在这种模式下,所有属性都被初始化。
当我有大量属性时,我更喜欢创建一个列表以便更容易阅读,如下所示:
My solution for this is:
In this mode, all attributes are initialized.
When I have a large number of attributes, I prefer to create a list to be easier to read like this: