Random/anonymous class methods
Ben Finney
bignose+hates-spam at benfinney.id.au
Sun Apr 27 10:14:02 EDT 2008
philly_bob <b0bm00r3 at gmail.com> writes:
> 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()
Functions (including methods) are objects, and can be referenced and
bound like any other object::
>>> import random
>>> class OptionDispatcher(object):
... def option_a(self):
... print "option a"
... def option_b(self):
... print "option b"
...
>>> dispatcher = OptionDispatcher()
>>> choice = dispatcher.option_a
>>> choice()
option a
>>> choice = dispatcher.option_b
>>> choice()
option b
>>> options = [dispatcher.option_a, dispatcher.option_b]
>>> choice = random.choice(options)
>>> choice()
option a
>>>
--
\ “I must say that I find television very educational. The |
`\ minute somebody turns it on, I go to the library and read a |
_o__) book.” —Groucho Marx |
Ben Finney
More information about the Python-list
mailing list