简体   繁体   English

kwargs 解析最佳实​​践

[英]kwargs parsing best practice

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]

To achieve exactly what you asked for, you could use要完全实现您的要求,您可以使用

for key in ('log', 'bin', 'pid', 'conf'):
    if key in kwargs:
        setattr(self, key, kwargs[key])

or或者

self.__dict__.update((key, kwargs[key])
                     for key in ('log', 'bin', 'pid', 'conf')
                     if key in kwargs)

However, I would generally prefer something like this:但是,我通常更喜欢这样的事情:

def f(log=None, bin=None, pid=None, conf=None):
    self.log = log
    self.bin = bin
    self.pid = pid
    self.conf = conf

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 = kwargs.get('log', default_log)
self.bin = kwargs.get('bin', default_bin)
self.pid = kwargs.get('pid', default_pid)
self.conf = kwargs.get('conf', default_conf)

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.).这有一个额外的好处,即在任何情况下都会分配self.logAttributeError意味着你的代码被破坏了,仅此而已。始终确保始终分配所有内容。)。 Without extra self.log = default_log lines.没有额外的self.log = default_log行。 You can omit the default to get None .您可以省略默认值以获取None

If the key provided in get() is not in the dictionary the result is None .如果get()提供的键不在字典中,则结果为None

self.log = kwargs.get('log')
self.bin = kwargs.get('bin')
self.pid = kwargs.get('pid')
self.conf = kwargs.get('conf')
for k,v in kwarg.iteritems():
   setattr(self, k, v)

In which setattr(self, "bin", "val") is like calling self.bin = "val"其中setattr(self, "bin", "val")就像调用self.bin = "val"

However it is more desirable to have a whitelist like @Sven Marnach has.然而,拥有像@Sven Marnach 这样的白名单是更可取的。

for k,v in kw.items():
   setattr(self, k, v)

self.__dict__.update(kwargs)

My solution for this is:我对此的解决方案是:

for key in ('log', 'bin', 'pid', 'conf'):
    setattr(self, key, kwargs.get(key, None))

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:当我有大量属性时,我更喜欢像这样创建一个更易于阅读的列表:

kwargs_list = [
    "log",
    "bin",
    "pin",
    "conf"
]

for key in kwargs_list:
    setattr(self, key, kwargs.get(key, None))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM