【问题标题】:Python attr - Choice of 2 attributesPython attr - 2 个属性的选择
【发布时间】:2021-06-28 07:54:22
【问题描述】:

我想创建一个包含 2 个可选属性的类,但至少有 1 个。我尝试了以下方法,但 attr 不允许这样做,并且不能确保至少有 1 个。

@attr.s
class myClass():
    attrA = attr.ib(default=None, validator=optional(instance_of(int)))
    attrB = attr.ib(default=None, validator=optional(instance_of(int)))

# Desired behaviour 
>>> a = myClass(attrA=1)
>>> a.attrA
1
>>> a.attrB
None

>>> a = myClass(attrB=2)
>>> a.attrA
None
>>> a.attrB
1

【问题讨论】:

    标签: python class attributes attr


    【解决方案1】:

    我不完全确定您展示的代码试图做什么,但无论如何都可以通过使用自定义初始化方法而不是 attr.s 装饰器来实现您的要求:

    class Myclass:
        def __init__(self, attrA=None, attrB=None):
           if not (attrA or attrB):
               raise ValueError('one of the attributes must be provided')
           self.attrA = attrA
           self.attrB = attrB
    

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多