Enum class with ToString functionality

TheFlyingDutchman zzbbaadd at aol.com
Mon Sep 10 17:11:37 EDT 2007


On Sep 8, 9:52 am, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> TheFlyingDutchman a écrit :
>
>
>
> > 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
>
> > class TestOutcomes:
> >     PASSED = 0
> >     FAILED = 1
> >     ABORTED = 2
>
> >     def ToString(outcome):
> >         if  outcome == TestOutcomes.PASSED:
> >            return "Passed"
> >         elif outcome == TestOutcomes.FAILED :
> >            return "Failed"
> >         else:
> >            return "Aborted"
>
> >     ToString = staticmethod(ToString)
>
> > if __name__ == "__main__":
> >     testResult = TestOutcomes.PASSED
> >     testResultAsString = TestOutcomes.ToString(testResult)
> >     print testResultAsString
> >     print TestOutcomes.ToString(testResult)
>
> Technically correct, but totally unpythonic.

Speaking of unpythonic, I would call

  ToString = staticmethod(ToString)

A Perlific syntax.

>
> May I suggest some reading ?http://dirtsimple.org/2004/12/python-is-not-java.html

Well the Foo.Foo complaint is bogus:

from Foo import Foo




More information about the Python-list mailing list