1

I have a Python enum:

class E(Enum):
  A = 1
  B = 2

It is part of a public interface, people pass E.A or E.B to various functions to specify some parameter. I want to augment this enum to add a third value, C, but this value only makes sense if you also pass a couple of additional parameters, x and y. So in addition to allowing my users to pass E.A or E.B, I want them to be able to pass e.g. E.C(x=17,y=42), and have my code access the values of these parameters (here, 17 and 42).

What's the most "pythonic" way of achieving this? I'm using Python 3.7.

4

1 回答 1

0

没有 Pythonic 方法可以实现这一点,因为您正试图以Enum不同于预期的方式使用。让我解释:

首先,一个具有更有用名称的枚举:

class Food(Enum):
    APPLE = 1
    BANANA = 2
    CARROT = 3

每个枚举成员(soAPPLEBANANA以上)都是一个单例——只有一个Food.APPLE、一个Food.BANANA和一个Food.CARROT(如果你添加它)。如果您将xandy属性添加到Food.CARROT,那么无论您在哪里使用,Food.CARROT您都会看到最后设置的内容。xy

例如,如果用func1调用和调用,那么当重新获得控制权时,它会看到和。func2Food.CARROT(17, 19)func2func3Food.CARROT(99, 101)func1Food.CARROT.x == 99Food.CARROT.y == 101

解决这个特定问题的方法就是将xandy参数添加到您的函数中,并让函数验证它们(就像您对任何其他有限制或要求的参数所做的那样)。

于 2021-11-08T22:00:22.083 回答