Newbie: switch question in Python
Darrell
news at dorb.com
Thu Dec 2 09:43:09 EST 1999
Instead of saving strings in the dictionary I'd save functions.
I'll demonstrate with an over the top example.
More than you wanted, I bet.
import string
def namelist(instance):
"""
Stolen from:
John Aycock http://www.csr.uvic.ca/~aycock/python/
Return a list of methods for instance
"""
namelist, classlist = [], [instance.__class__]
dic={}
for c in classlist:
for b in c.__bases__:
classlist.append(b)
for i in dir(c):
if not dic.has_key(i):
dic[i]=1
namelist.append(i)
for k,v in instance.__dict__.items():
if type(v)==types.FunctionType or type(v)==types.MethodType:
namelist.append(k)
return namelist
class Switch:
"""
Derived classes should have methods that begin with "case_"
and have a trailing digit. e.g. "case_55"
These methods will be searched by the __call__ method.
For a match on the trailing digit with val passed into __call__
"""
def __init__(self, prefix='case_'):
names=namelist(self)
swDic={}
for n in names:
if string.find(n, prefix) != -1:
s=string.split(n,'_')
try:
key=string.atoi(s[-1])
except ValueError:
raise 'Method name error. Try "case_2"'
swDic[key]=getattr(self,n)
self._switch=swDic
def __call__(self, val):
try:
self._switch[val]()
except KeyError:
self.default(val)
class MySwitch(Switch):
def __init__(self):
Switch.__init__(self)
def case_1(self):
print 'Case_1'
def case_2(self):
print 'Case_2'
def case_3(self):
print 'Case_3'
def default(self, val):
print 'Key"%d" was found here!'%val
def test1():
mySwtich=MySwitch()
for x in range(5):
mySwtich(x)
test1()
"""
Key"0" was found here!
Case_1
Case_2
Case_3
Key"4" was found here!
"""
--
--Darrell
"William J. King" <wjk at wjk.mv.com> wrote in message
news:384605BC.56EAB34E at wjk.mv.com...
> Hi again! I was reading a tutorial that said
> there was no switch statement in Python...and
> that I could use a 'conditional' if else etc.
> -- so I wrote a switch and would like to know if
> its ok to do this or if you have any other better
> ideas... Thanks to all for their help in learning
> Python in the past 2 weekends....
More information about the Python-list
mailing list