enum question

M

M.N.A.Smadi

does python support a C-like enum statement where one can define a
variable with prespesified range of values?

thanks
m.smadi
 
L

Larry Bates

Not completely sure I understand (my C is weak).
But you can do:

x=range(9)

x's contents will be
[0,1,2,3,4,5,6,7,8]

or

x=range(12,25)

x's conetnst will be
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

if you mean a way to limit x's contents to a predefined
list of values, you need to write a class for that and
override the __setattr__ method to limit. Quick
example:

class a:
def __setattr__(self, attr, x):
if x in range(10): self.__dict__[attr]=x
else:
print "error, x not in ", str(range(10))
x=a()
x.value=11 error, x not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x.value=8

Larry Bates
 
P

Patrick Useldinger

M.N.A.Smadi said:
does python support a C-like enum statement where one can define a
variable with prespesified range of values?

thanks
m.smadi
8
 
C

Carl Banks

M.N.A.Smadi said:
does python support a C-like enum statement where one can define a
variable with prespesified range of values?

The thing is, variables don't have types; objects do. A variable can
be bound to an object of any type, so there's no way to prespecify a
range of values for a variable.

Your question has the air of someone who's evaluating Python features,
considering whether to try it. If so, you might need to widen your
worldview a little to understand Python; its variables are
fundamentally different from C, and things like enums don't make much
sense in Python because of it. However, Python is versatile enough
that you can get something to that effect if you really need it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
474,222
Messages
2,571,137
Members
47,754
Latest member
Armand37T7

Latest Threads

Top