简体   繁体   English

Python 具有多个属性的枚举

[英]Python Enum with multiple attributes

I have his Enum:我有他的枚举:

class MultiAttr(Enum):
    RED = (1, 10)
    GREEN = (2, 20)
    BLUE = (3, 20)
    def __init__(self, id, val):
        self.id = id
        self.val = val
assert MultiAttr((2, 20)) == MultiAttr.GREEN

Assertion passes.断言通过。

  1. Why Pylance in VSCode complains Argument missing for parameter "val" ?为什么 VSCode 中的 Pylance 会抱怨Argument missing for parameter "val"
  2. As the first attribute is the identifer, is there a way to achieve: MultiAttr(2) == MultiAttr.GREEN ?由于第一个属性是标识符,有没有办法实现: MultiAttr(2) == MultiAttr.GREEN

You could make use of __new__ , as you want to customize the actual value of the Enum member:您可以使用__new__ ,因为您想自定义 Enum 成员的实际值:

from enum import Enum

class MultiAttr(bytes, Enum):
    def __new__(cls, value, otherVal):
        obj = bytes.__new__(cls, [value])
        obj._value_ = value
        obj.otherVal = otherVal
        return obj
    RED = (1, 10)
    GREEN = (2, 20)
    BLUE = (3, 20)


print(MultiAttr(2) == MultiAttr.GREEN)
print(MultiAttr(2).otherVal)

Out:出去:

True
20

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

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