473,406 Members | 2,894 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Random/anonymous class methods

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()
Jun 27 '08 #1
4 1481
philly_bob <b0******@gmail.comwrites:
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
Jun 27 '08 #2
philly_bob <b0******@gmail.comwrites:
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
Jun 27 '08 #3
On Apr 27, 7:11*am, Arnaud Delobelle <arno...@googlemail.comwrote:
philly_bob <b0bm0...@gmail.comwrites:
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- 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?
Jun 27 '08 #4
On Apr 27, 8:05 am, philly_bob <b0bm0...@gmail.comwrote:
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()

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.meth 2,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'

Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
by: Grzegorz Staniak | last post by:
Hello, I'm a newbie Python user, a systems administrator - I've been trying to switch from Perl to Python for administrative tasks - and one thing I cannot understand so far is why I need the...
4
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned...
0
by: Carlos Ribeiro | last post by:
I thought about this problem over the weekend, after long hours of hacking some metaclasses to allow me to express some real case data structures as Python classes. I think that this is something...
2
by: Craig Ringer | last post by:
Hi folks I've been doing some looking around, but have been unable to find out how to implement class methods on Python objects written in C. "Why are you using C?" you ask? Yeah, so do I....
18
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I...
6
by: Christopher Bohn | last post by:
It looks like the c++ source for a single object file can not contain more than one anonymous class that derives from a base class. When I attempted to do this, the linker failed with the...
10
by: David Hirschfield | last post by:
Here's a strange concept that I don't really know how to implement, but I suspect can be implemented via descriptors or metaclasses somehow: I want a class that, when instantiated, only defines...
4
by: josh | last post by:
Hi, is there the possibility to create anonymous class (not object) in C++ like do Java? as an example: in Java if I do: // here Shape is an Interface that is like a c++ class wih only pure...
20
by: vbgunz | last post by:
I remember learning closures in Python and thought it was the dumbest idea ever. Why use a closure when Python is fully object oriented? I didn't grasp the power/reason for them until I started...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.