如何将 **kwargs 复制到自身?
有没有一种方法可以定义 __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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想在stackoverflow上的某个地方我已经看到了这样的解决方案。无论如何,它看起来像:
此类仅接受具有
__allowed
中列出的白名单属性名称的参数。I think somewhere on the stackoverflow I've seen such solution. Anyway it can look like:
This class will only accept arguments with a whitelisted attribute names listed in
__allowed
.这可能不是最干净的方法,但它有效:
我想我更喜欢 ony 的解决方案 因为它限制了可用的属性,以便在您的输入来自外部源时避免出现麻烦。
This may not be the cleanest way, but it works:
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.
你可以这样做:
You could do something like this:
您可以通过更新实例的 __dict__ 属性来设置您的 kwargs 参数。
You can set your
kwargs
arguments by updating__dict__
attribute of the instance.这可以被认为比更新 __dict__ 更好:
This could be considered nicer than updating
__dict__
:我发现上面的答案很有帮助,然后进行了改进:
测试:
并且验证也在那里:
I found the above answers helpful and then refined:
Test:
And validation is also there: