Enum class with ToString functionality

J. Cliff Dyer jcd at sdf.lonestar.org
Tue Sep 11 06:53:50 EDT 2007


Zara wrote:
> On Mon, 10 Sep 2007 02:28:57 -0700, 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 should implement __str__ (or __repr__) method in your class, 
>
> class TestOutcomes:
>     PASSED = 0
>     FAILED = 1
>     ABORTED = 2
>
>    def __str__(self):
>       textResultAsString="Unknown"
>       if  testResult == TestOutcomes.PASSED:
>          testResultAsString = "Passed"
>       elif testResult == TestOutcomes.FAILED :
>          testResultAsString = "Failed"
>       else:
>          testResultAsString = "Aborted"
>       return testResultAsString
>
> Regards,
>
> Zara
>
>   
This code cannot output "Unknown," because you use an else: at the end
of your if-chain to represent a specific (non-catch-all) case. 

s/else:/elif testResult == TestOutcomes.ABORTED:/

Cheers,
Cliff



More information about the Python-list mailing list