2024-09-26 22:49:31 发布
网友
我在一个类中设置枚举值有困难。。。在
如果我在iPython窗口中:
eTest = Enum('zero', 'one', 'two', 'three')
我可以:
并且print eTest.value给出了正确的答案:2
print eTest.value
我在python类中也尝试了同样的方法,它告诉我:
AttributeError: 'str' object has no attribute 'values'
如何将eTest设置为拥有枚举的[3]值而不必键入单词“three”?在
不能像这样使用Enum对象。Enum对象只是一种声明,它告诉HasTraits类具有其中一个来生成执行特定类型验证的实例属性。这个实例属性将是一个Enum对象:它将是枚举值之一。您在Enum对象上修改的.value属性只会更改的默认值。它不是你在对象的生命周期内设置的。在
Enum
HasTraits
.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()调用分开,并在需要时索引到它。在
Enum()
不能像这样使用
Enum
对象。Enum
对象只是一种声明,它告诉HasTraits
类具有其中一个来生成执行特定类型验证的实例属性。这个实例属性将是一个Enum
对象:它将是枚举值之一。您在Enum
对象上修改的.value
属性只会更改的默认值。它不是你在对象的生命周期内设置的。在您可以按照我上面的例子,将列表与
Enum()
调用分开,并在需要时索引到它。在相关问题 更多 >
编程相关推荐