Enum class with ToString functionality

aine_canby at yahoo.com aine_canby at yahoo.com
Mon Sep 10 07:38:07 EDT 2007


On 10 Sep, 13:35, TheFlyingDutchman <zzbba... at aol.com> wrote:
> On Sep 10, 2:28 am, bg... 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?
>
> > Thanks,
>
> > Barry
>
> The equivalent to Java's toString() is __str__() in Python:
>
> class TestOutcomes:
>     PASSED = 0
>     FAILED = 1
>     ABORTED = 2
>
>     def __init__(self,outcome):
>         self.outcome = outcome
>
>     def __str__(self):
>         if  self.outcome == TestOutcomes.PASSED:
>            return "Passed"
>         elif self.outcome == TestOutcomes.FAILED :
>            return "Failed"
>         else:
>            return "Aborted"
>
> if __name__ == "__main__":
>     testResult = TestOutcomes(TestOutcomes.ABORTED)
>     print testResult
>     testResult = TestOutcomes(TestOutcomes.FAILED)
>     a = testResult.__str__()
>     print a
>
> Aborted
> Failed- Dölj citerad text -
>
> - Visa citerad text -

Would this be crazy? -

class TestOutcomes:
    PASSED = "PASSED"
    FAILED = "FAILED"
    ABORTED = "ABORTED"




More information about the Python-list mailing list