Enum class with ToString functionality

Zara me_zara at dea.spamcon.org
Mon Sep 10 12:27:52 CEST 2007


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




More information about the Python-list mailing list