如何从python中的变量参数(kwargs)设置类属性 [英] How can you set class attributes from variable arguments (kwargs) in python

查看:49
本文介绍了如何从python中的变量参数(kwargs)设置类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有构造函数(或其他函数)的类,它接受可变数量的参数,然后有条件地将它们设置为类属性.

我可以手动设置它们,但似乎变量参数在python中很常见,因此应该有一个通用的习惯用法来执行此操作.但我不确定如何动态执行此操作.

我有一个使用 eval 的示例,但这并不安全.我想知道这样做的正确方法——也许使用 lambda?

 Foo 类:def setAllManually(self, a=None, b=None, c=None):如果 a!=None:self.a = a如果 b!=无:自我.b = b如果 c!=无:self.c = cdef setAllWithEval(self, **kwargs):对于 **kwargs 中的关键:如果 kwargs[param] != 无eval("self." + key + "=" + kwargs[param])

解决方案

您可以使用关键字参数更新 __dict__ 属性(以字典形式表示实例属性):

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

那么你可以:

<预><代码>>>>bar = Bar(a=1, b=2)>>>酒吧.a1

还有类似的东西:

allowed_keys = {'a', 'b', 'c'}self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys)

您可以预先过滤键(如果您仍在使用 Python 2.x,请使用 iteritems 而不是 items).

Suppose I have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally.

I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure how to do this dynamically.

I have an example using eval, but that's hardly safe. I want to know the proper way to do this -- maybe with lambda?

class Foo:
    def setAllManually(self, a=None, b=None, c=None):
        if a!=None: 
            self.a = a
        if b!=None:
            self.b = b
        if c!=None:
            self.c = c
    def setAllWithEval(self, **kwargs):
        for key in **kwargs:
            if kwargs[param] != None
                eval("self." + key + "=" + kwargs[param])

解决方案

You could update the __dict__ attribute (which represents the instance attributes in the form of a dictionary) with the keyword arguments:

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

then you can:

>>> bar = Bar(a=1, b=2)
>>> bar.a
1

and with something like:

allowed_keys = {'a', 'b', 'c'}
self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys)

you could filter the keys beforehand (use iteritems instead of items if you’re still using Python 2.x).

这篇关于如何从python中的变量参数(kwargs)设置类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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