473,785 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Enum class with ToString functionality

Hi,

I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PA SSED

testResultAsStr ing
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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

Sep 10 '07 #1
15 2999
bg***@yahoo.com wrote:
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?
Perhaps: http://aspn.activestate.com/ASPN/Coo.../Recipe/413486
Sep 10 '07 #2
On 9/10/07, bg***@yahoo.com <bg***@yahoo.co mwrote:
Hi,

I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PA SSED

testResultAsStr ing
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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.
Sep 10 '07 #3
On Sep 10, 2:28 am, bg...@yahoo.com wrote:
Hi,

I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PA SSED

testResultAsStr ing
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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,o utcome):
self.outcome = outcome

def __str__(self):
if self.outcome == TestOutcomes.PA SSED:
return "Passed"
elif self.outcome == TestOutcomes.FA ILED :
return "Failed"
else:
return "Aborted"

if __name__ == "__main__":
testResult = TestOutcomes(Te stOutcomes.ABOR TED)
print testResult
testResult = TestOutcomes(Te stOutcomes.FAIL ED)
a = testResult.__st r__()
print a

Aborted
Failed
Sep 10 '07 #4
On 10 Sep, 13:35, TheFlyingDutchm an <zzbba...@aol.c omwrote:
On Sep 10, 2:28 am, bg...@yahoo.com wrote:


Hi,
I have the following class -
class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2
plus the following code -
testResult = TestOutcomes.PA SSED
testResultAsStr ing
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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,o utcome):
self.outcome = outcome

def __str__(self):
if self.outcome == TestOutcomes.PA SSED:
return "Passed"
elif self.outcome == TestOutcomes.FA ILED :
return "Failed"
else:
return "Aborted"

if __name__ == "__main__":
testResult = TestOutcomes(Te stOutcomes.ABOR TED)
print testResult
testResult = TestOutcomes(Te stOutcomes.FAIL ED)
a = testResult.__st r__()
print a

Aborted
Failed- Dölj citerad text -

- Visa citerad text -
Would this be crazy? -

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

Sep 10 '07 #5
On Sep 10, 2:28 am, bg...@yahoo.com wrote:
Hi,

I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PA SSED

testResultAsStr ing
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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(outcom e):
if outcome == TestOutcomes.PA SSED:
return "Passed"
elif outcome == TestOutcomes.FA ILED :
return "Failed"
else:
return "Aborted"

ToString = staticmethod(To String)

if __name__ == "__main__":
testResult = TestOutcomes.PA SSED
testResultAsStr ing = TestOutcomes.To String(testResu lt)
print testResultAsStr ing
print TestOutcomes.To String(testResu lt)
Passed
Passed

Sep 10 '07 #6
bg***@yahoo.com wrote:
I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PA SSED

testResultAsStr ing
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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?
Why don't use the simple approach like this?

TEST_PASSED = "Passed"
TEST_FAILED = "Failed"
TEST_ABORTED = "Aborted"

In Python, no one forces you to put everything in classes.

If you are determined to use the class approach, use the __str__
method. It's called when you do str(instance).

Regards,
Björn

--
BOFH excuse #122:

because Bill Gates is a Jehovah's witness and so nothing can work on
St. Swithin's day.

Sep 10 '07 #7
TheFlyingDutchm an a écrit :
On Sep 10, 2:28 am, bg...@yahoo.com wrote:
>>Hi,

I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PA SSED

testResultAsS tring
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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(outcom e):
if outcome == TestOutcomes.PA SSED:
return "Passed"
elif outcome == TestOutcomes.FA ILED :
return "Failed"
else:
return "Aborted"

ToString = staticmethod(To String)

if __name__ == "__main__":
testResult = TestOutcomes.PA SSED
testResultAsStr ing = TestOutcomes.To String(testResu lt)
print testResultAsStr ing
print TestOutcomes.To String(testResu lt)
Technically correct, but totally unpythonic.

May I suggest some reading ?
http://dirtsimple.org/2004/12/python-is-not-java.html
Sep 10 '07 #8
On Sep 8, 9:52 am, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
TheFlyingDutchm an a écrit :
On Sep 10, 2:28 am, bg...@yahoo.com wrote:
>Hi,
>I have the following class -
>class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2
>plus the following code -
>testResult = TestOutcomes.PA SSED
>testResultAsSt ring
if testResult == TestOutcomes.PA SSED:
testResultAsStr ing = "Passed"
elif testResult == TestOutcomes.FA ILED :
testResultAsStr ing = "Failed"
else:
testResultAsStr ing = "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(outcom e):
if outcome == TestOutcomes.PA SSED:
return "Passed"
elif outcome == TestOutcomes.FA ILED :
return "Failed"
else:
return "Aborted"
ToString = staticmethod(To String)
if __name__ == "__main__":
testResult = TestOutcomes.PA SSED
testResultAsStr ing = TestOutcomes.To String(testResu lt)
print testResultAsStr ing
print TestOutcomes.To String(testResu lt)

Technically correct, but totally unpythonic.
Speaking of unpythonic, I would call

ToString = staticmethod(To String)

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

Sep 10 '07 #9
bg***@yahoo.com writes:
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?
Others have given ad hoc implementations that may do what you want.

I'd like to know if the Cheeseshop package 'enum' is useful to
you. Any constructive feedback would be appreciated.

<URL:http://cheeseshop.pyth on.org/pypi/enum/>

--
\ "Remorse: Regret that one waited so long to do it." -- Henry |
`\ L. Mencken |
_o__) |
Ben Finney
Sep 11 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7350
by: Suresh | last post by:
Hi, I need to add a custom ToString method on an Enum Property. The default ToString method expands the whole name. But, I want only an short associated code with the long name of the enum type. For example, public enum Color { Red = 0, Blue, Green } The statement
21
4607
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
9
39741
by: Lawrence Oluyede | last post by:
I have a list of strings and i'd like to build up an enum from them... is there a way to do that? Thanks in advance. -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com
5
2874
by: Barry | last post by:
Hello, In VS2003, I tried using an enum and setting it into a field in a datarow. It seems as if the datatype of the field in the row determined what went into the field. If the datatype was string, then the name of the enum item went into the field, but if the datatype was integer, then the integer value of the enum was stored. Is this expected behaviour? I couldn't find anything while searching for answers.
6
3003
by: giannik | last post by:
I have an Enum Structure Public Enum MyEnum EnumVal1=0 EnumVal2=1 EnumVal2=2 end enum I save in an access database this enum value as an integer (0=EnumVal1,
7
9837
by: Harris | last post by:
Dear all, I have the following codes: ====== public enum Enum_Value { Value0 = 0, Value1 = 10,
34
11205
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code snippet that I wrote today that gives me an instant implementation of the pattern. I could easily just always use such an implementation instead of a standard enum, so I wanted to know what you experts all thought. Is there a case for standard enums?
3
3046
by: hufaunder | last post by:
Imagine you have a charting library that can draw lines, bars, floating bars, bands, etc. Lines and bars need only one input. Floating bars and bands need two inputs. There are two approaches: 1) One enum with all 4 types (bars, band, etc). One chart class that accepts up to 2 arrays of values. If the user choses a band but there is only one input array throw an exception. If the user passes two input arrays with different lengths throw...
3
1289
by: Ralfeus | last post by:
Hi all Oftenly I need to use enums but standard C# enums provide little bit poor possibilities. For example I'd like to restrict variables to get only values specified in enums. Also sometimes I want to implement some type conversion from enum to some other type. Is it possible to create a new type, which would extend an enum? Thanks
0
10336
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10095
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8978
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.