Enum class with ToString functionality

David wizzardx at gmail.com
Mon Sep 10 07:30:56 EDT 2007


On 9/10/07, bg_ie at yahoo.com <bg_ie at yahoo.com> wrote:
> Hi,
>
> I have the following class -
>
> class TestOutcomes:
>     PASSED = 0
>     FAILED = 1
>     ABORTED = 2
>
> plus the following code -
>
> testResult = TestOutcomes.PASSED
>
> testResultAsString
> if  testResult == TestOutcomes.PASSED:
>     testResultAsString = "Passed"
> elif testResult == TestOutcomes.FAILED :
>     testResultAsString = "Failed"
> else:
>     testResultAsString = "Aborted"
>
> But it would be much nicer if I had a function to covert to string as
> part of the TestOutcomes class. How would I implement this?

You can use reflection to do this. Perhaps a constructor that goes
through your class dict (dir(self)) and builds an int->string mapping
property based on the value and name of the attributes (perhaps just
the ones whose type is int). To get the exact same result as your code
above you can capitalize the first letter of the attribute name, and
lowercase the rest.



More information about the Python-list mailing list