Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Random/anonymous class methods

2 views
Skip to first unread message

philly_bob

unread,
Apr 27, 2008, 8:05:10 AM4/27/08
to
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()

Arnaud Delobelle

unread,
Apr 27, 2008, 8:11:27 AM4/27/08
to
philly_bob <b0bm...@gmail.com> writes:

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

Ben Finney

unread,
Apr 27, 2008, 10:14:02 AM4/27/08
to
philly_bob <b0bm...@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

casti...@gmail.com

unread,
Apr 27, 2008, 10:17:01 AM4/27/08
to
On Apr 27, 7:11 am, Arnaud Delobelle <arno...@googlemail.com> wrote:
> Arnaud- Hide quoted text -
>
> - Show quoted text -

MethodType constructors can't be subclassed nor aren't guaranteed
consistent. Inferrably, it's because there's more than one way to do
it.

The way C used to do it was by ordinal, which turns into Java-style
reflection. If you use non-linear operation time, string lookup can
actually exceed running value of the dollar that Python is on. Do you
want the reliability of compile-time errors to do brainwork? If
you're chasing running time on member look-up, you may be at an Python
entry bottleneck. The class is the only structure that knows what
function to run on what object.

If you are looking for just a clean -syntax- to denote a uni-
dimensional bit by a string of symbols (write 'that' down), you would
keep methods in synch across *del+setattr*, specifically, changes.

To walk through it: you have a method name from an unknown source, and
you want to know different addresses of functions with that name.

>>> read 'foo'.
'foo' is a method of more than one object.
>>> 'bar'.'foo'
'foo' method of 'bar'.
>>> 'cat'.'foo'
'foo' method of 'cat'
>>> call cat.foo a thousand times

What steps did the interpreter take?

If you mutate 'foo', what should 'cat'.'foo' do? Strings aren't
immutable in the generic language.

If you mutate 'cat', what should 'cat'.'foo' do? If you keep a
('cat','foo') pair in memory (which is why I keep metioning two-
dimensional arrays, they're just sparsely populated), you can hash the
intersection to a specific bit, but it may not be faster than hash
lookups on 'cat' and 'foo' combined. Won't you change the contents of
'cat'?

An object-method pair-wise lookup could make more bucks. Do you want
more than two? Isn't a generic n-dimensional lookup from linear
memory a hash table anyway?

You make a case that rigid static lookups are live and useful, and
someone else makes the case that users like dynamic lookups, perhaps a
more even cross-section of them or something. Rigid statics would be
in hardware. Can Python live if hardware comes to support it?

philly_bob

unread,
May 5, 2008, 5:04:23 PM5/5/08
to


Thanks for your responses, everybody. Turned out to be easiest to use
Arnaud's Getattr suggestion. Below is a simplification of what I
ended up with; the trick appears in the algday class.

"""
I have dictionaries of OHLC tuples (open, high, low, close market
prices) for two hypothetical stocks (HUN and TEN); the dictionaries
are keyed to dates.

For each day that we have data, we want to be able to evaluate an
algorithm of the form:

(mysum 'HUN' 'open' 'TEN', close)

in other words, to add the opening value of HUN to the closing value
of TEN.

Stock names and market values are stored in two lists: namelist and
valuelist. Namelist contains the stock symbols (HUN, TEN). Valuelist
contains dictionaries keyed to dates. Associated in the dictionary
with
each date is a tuple containing OHLC prices. Note that even in this
sample
we have to allow for days when one stock has market values
and the other stock doesn't, as in the case of 20080424.

We use a class algday, which, given an algorithm and day, has a method
calc() which returns the result of applying that algorithm to the day.
This class (algday) uses another class, namedayval, which, given a
stock name and a
OHLC valuename, returns the value.

=Bob Moore
Thanks to Arnaud Delobelle, Aaron Brady, and Ben Finney.

"""

import random

class namedayvals(object):
def __init__(self,name,date):
self.name=name
self.date=date
self.index=namelist.index(name)
self.valuelist=valuelist[self.index]
self.dayswithvals=self.valuelist.keys()
def open(self):
if self.date not in self.dayswithvals:
return 'NA'
else:
return self.valuelist[self.date][0]
def high(self):
if self.date not in self.dayswithvals:
return 'NA'
else:
return self.valuelist[self.date][1]
def low(self):
if self.date not in self.dayswithvals:
return 'NA'
else:
return self.valuelist[self.date][2]
def close(self):
if self.date not in self.dayswithvals:
return 'NA'
else:
return self.valuelist[self.date][3]

class algday(object):
def __init__(self,myop,sec1,meth1,sec2,meth2,date):
self.myop=myop
self.sec1=sec1
self.meth1=meth1
self.sec2=sec2
self.meth2=meth2
self.date=date
def show(self):
print 'algday',
self.myop,self.sec1,self.meth1,self.sec2,self.meth2,self.date
def calc(self):
s1=namedayvals(self.sec1, self.date)
x1=getattr(s1,self.meth1)()
s2=namedayvals(self.sec2, self.date)
x2=getattr(s2,self.meth2)()
if self.myop=='mysum':
out=mysum(x1,x2)
elif self.myop=='myless':
out=myless(x1,x2)
elif self.myop=='mydiv':
out=mydiv(x1,x2)
elif self.myop=='mytimes':
out=mytimes(x1,x2)
else:
out='NA'
return out

def mydiv(num1, num2):
if num1=='NA' or num2=='NA':
temp='NA'
else:
if num2==0:
temp=0.0
else:
temp=float(num1)/float(num2)
return temp

def myless(num1,num2):
if num1=='NA' or num2=='NA':
temp='NA'
else:
temp=num1-num2
return temp

def mytimes(num1,num2):
if num1=='NA' or num2=='NA':
temp='NA'
else:
temp=num1*num2
return temp

def mysum(num1,num2):
if num1=='NA' or num2=='NA':
temp='NA'
else:
temp=num1*num2
return temp

#####

namelist=[]
valuelist=[]
namelist.append('HUN')
valuelist.append(dict({'20080422': (100.1,100.2,100.3,100.4),
'20080423': (101.1,101.2,101.3,101.4),
'20080424': (102.1,102.2,102.3,102.4)}))
namelist.append('TEN')
valuelist.append(dict({'20080422': (10.1,10.2,10.3,10.4),
'20080423': (11.1,11.2,11.3,11.4)}))

operatorlist=['mydiv','mysum','myless','mytimes']
valuenames=['open','high','low','close']
daylist=['20080422','20080423','20080424']

while 1:
rop=random.choice(operatorlist)
rn1=random.choice(namelist)
rv1=random.choice(valuenames)
rn2=random.choice(namelist)
rv2=random.choice(valuenames)
print rop,rn1,rv1,rn2,rv2
calcs=[]
for date in daylist:
a=algday(rop,rn1,rv1,rn2,rv2,date)
calcs.append([date,a.calc()])
print 'daily calcs=', calcs
print 'Control-C to stop'

0 new messages