I'm having trouble setting an Enum value to one of it's possibility in a class...
If I have in an iPython window:
eTest = Enum('zero', 'one', 'two', 'three')
I can do:
eTest.value = eTest.values[2]
and print eTest.value
gives me the correct answer: two
I'm trying the same thing in a python class, and it tells me that:
AttributeError: 'str' object has no attribute 'values'
how can I set eTest to have the [3] value of the Enums without having to type in the word 'three'?
You do not work with Enum
objects like this. The Enum
object is just a kind of declaration that tells the HasTraits
class that has one of these to make an instance attribute that does a particular kind of validation. This instance attribute will not be an Enum
object: it will be one of the enumerated values. The .value
attribute that you were modifying on the Enum
object just changes what the default value is going to be. It's not something you set during the lifetime of your object.
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'?
You can follow my example above and keep the list separate from the Enum()
call and just index into it when you need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With