特征枚举值

2024-09-26 22:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个类中设置枚举值有困难。。。在

如果我在iPython窗口中:

eTest = Enum('zero', 'one', 'two', 'three')

我可以:

^{pr2}$

并且print eTest.value给出了正确的答案:2

我在python类中也尝试了同样的方法,它告诉我:

AttributeError: 'str' object has no attribute 'values'

如何将eTest设置为拥有枚举的[3]值而不必键入单词“three”?在


Tags: 方法答案objectvalueipythonenumonethree
1条回答
网友
1楼 · 发布于 2024-09-26 22:49:31

不能像这样使用Enum对象。Enum对象只是一种声明,它告诉HasTraits类具有其中一个来生成执行特定类型验证的实例属性。这个实例属性将是一个Enum对象:它将是枚举值之一。您在Enum对象上修改的.value属性只会更改的默认值。它不是你在对象的生命周期内设置的。在

from traits.api import Enum, HasTraits, TraitError


ETEST_VALUES = ['zero', 'one', 'two', 'three']


class Foo(HasTraits):
    eTest = Enum(*ETEST_VALUES)


f = Foo()
assert f.eTest == 'zero'
f.eTest = 'one'
f.eTest = ETEST_VALUES[3]

try:
    f.eTest = 'four'
except TraitError:
    print 'Oops! Bad value!'

how can I set eTest to have the [3] value of the Enums without having to type in the word 'three'?

您可以按照我上面的例子,将列表与Enum()调用分开,并在需要时索引到它。在

相关问题 更多 >

    热门问题