如何将 **kwargs 复制到自身?

发布于 2024-08-26 12:23:42 字数 356 浏览 8 评论 0原文

有没有一种方法可以定义 __init__ 以便将 **kwargs 中定义的关键字分配给该类?

例如,如果我要使用 ValidationRule(other='email') 初始化 ValidationRule 类,则 self.other 的值应为添加到类中,而不必显式命名每个可能的 kwarg。

class ValidationRule:
    def __init__(self, **kwargs):
        # code to assign **kwargs to .self

Is there a way that I can define __init__ so keywords defined in **kwargs are assigned to the class?

For example, if I were to initialize a ValidationRule class with ValidationRule(other='email'), the value for self.other should be added to the class without having to explicitly name every possible kwarg.

class ValidationRule:
    def __init__(self, **kwargs):
        # code to assign **kwargs to .self

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

彩虹直至黑白 2024-09-02 12:23:42

我想在stackoverflow上的某个地方我已经看到了这样的解决方案。无论如何,它看起来像:

class ValidationRule:
    __allowed = ("other", "same", "different")
    def __init__(self, **kwargs):
        for k, v in kwargs.iteritems():
            assert( k in self.__class__.__allowed )
            setattr(self, k, v)

此类仅接受具有 __allowed 中列出的白名单属性名称的参数。

I think somewhere on the stackoverflow I've seen such solution. Anyway it can look like:

class ValidationRule:
    __allowed = ("other", "same", "different")
    def __init__(self, **kwargs):
        for k, v in kwargs.iteritems():
            assert( k in self.__class__.__allowed )
            setattr(self, k, v)

This class will only accept arguments with a whitelisted attribute names listed in __allowed.

幻梦 2024-09-02 12:23:42

这可能不是最干净的方法,但它有效:

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

我想我更喜欢 ony 的解决方案 因为它限制了可用的属性,以便在您的输入来自外部源时避免出现麻烦。

This may not be the cleanest way, but it works:

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

I think I prefer ony's solution because it restricts available properties to keep you out of trouble when your input comes from external sources.

风吹过旳痕迹 2024-09-02 12:23:42

你可以这样做:

class ValidationRule:
   def __init__(self, **kwargs):
      for (k, v) in kwargs.items():
         setattr(self, k, v)

You could do something like this:

class ValidationRule:
   def __init__(self, **kwargs):
      for (k, v) in kwargs.items():
         setattr(self, k, v)
沉睡月亮 2024-09-02 12:23:42
class ValidationRule:
   def __init__(self, **kwargs):
      self.__dict__.update(kwargs)
class ValidationRule:
   def __init__(self, **kwargs):
      self.__dict__.update(kwargs)
素染倾城色 2024-09-02 12:23:42

您可以通过更新实例的 __dict__ 属性来设置您的 kwargs 参数。

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

You can set your kwargs arguments by updating __dict__ attribute of the instance.

class ValidationRule:
   def __init__(self, **kwargs):
       self.__dict__.update(kwargs)
浮生面具三千个 2024-09-02 12:23:42

这可以被认为比更新 __dict__ 更好:

class C:
    def __init__(self, **kwargs):
        vars(self).update(kwargs)

>>> c = C(a='a', b='b')
>>> c.a   # returns 'a'
>>> c.b   # returns 'b'

This could be considered nicer than updating __dict__:

class C:
    def __init__(self, **kwargs):
        vars(self).update(kwargs)

>>> c = C(a='a', b='b')
>>> c.a   # returns 'a'
>>> c.b   # returns 'b'
尘曦 2024-09-02 12:23:42

我发现上面的答案很有帮助,然后进行了改进:

class MyObj(object):
    def __init__(self, key1=1, key2=2, key3=3):
        for (k, v) in locals().iteritems():
            if k != 'self':
                setattr(self, k, v)

测试:

>>> myobj = MyObj(key1=0)
>>> print myobj.key1
0

并且验证也在那里:

>>> myobj = MyObj(key4=4)
TypeError: __init__() got an unexpected keyword argument 'key4'

I found the above answers helpful and then refined:

class MyObj(object):
    def __init__(self, key1=1, key2=2, key3=3):
        for (k, v) in locals().iteritems():
            if k != 'self':
                setattr(self, k, v)

Test:

>>> myobj = MyObj(key1=0)
>>> print myobj.key1
0

And validation is also there:

>>> myobj = MyObj(key4=4)
TypeError: __init__() got an unexpected keyword argument 'key4'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文