Random/anonymous class methods
Arnaud Delobelle
arnodel at googlemail.com
Sun Apr 27 08:11:27 EDT 2008
philly_bob <b0bm00r3 at gmail.com> writes:
> In the sample program below, I want to send a random method to a class
> instance.
> In other words, I don't know which method to send until run-time. How
> can I send ch, which is my random choice, to the myclass instance?
>
> Thanks,
>
> Bob=
>
> ####
> import random
>
> class myclass(object):
> def meth1(self):
> print 'meth1'
> def meth2(self):
> print 'meth2'
>
> c=myclass()
> meths=['meth1', 'meth2']
> ch=random.choice(meths)
> c.ch()
This will work:
getattr(c, ch)()
Getattr(c, "meth1") is equivalent to c.meth1. Or you could do:
meths = [c.meth1, c.meth2]
ch = random.choice(meths)
ch()
--
Arnaud
More information about the Python-list
mailing list