473,749 Members | 2,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.choic e(meths)
c.ch()
Jun 27 '08 #1
4 1501
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.choic e(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(m eths)
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.choic e(meths)
c.ch()
Functions (including methods) are objects, and can be referenced and
bound like any other object::
>>import random
class OptionDispatche r(object):
... def option_a(self):
... print "option a"
... def option_b(self):
... print "option b"
...
>>dispatcher = OptionDispatche r()
choice = dispatcher.opti on_a
choice()
option a
>>choice = dispatcher.opti on_b
choice()
option b
>>options = [dispatcher.opti on_a, dispatcher.opti on_b]
choice = random.choice(o ptions)
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...@google mail.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.choic e(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(m eths)
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.choic e(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(obj ect):
def __init__(self,n ame,date):
self.name=name
self.date=date
self.index=name list.index(name )
self.valuelist= valuelist[self.index]
self.dayswithva ls=self.valueli st.keys()
def open(self):
if self.date not in self.dayswithva ls:
return 'NA'
else:
return self.valuelist[self.date][0]
def high(self):
if self.date not in self.dayswithva ls:
return 'NA'
else:
return self.valuelist[self.date][1]
def low(self):
if self.date not in self.dayswithva ls:
return 'NA'
else:
return self.valuelist[self.date][2]
def close(self):
if self.date not in self.dayswithva ls:
return 'NA'
else:
return self.valuelist[self.date][3]

class algday(object):
def __init__(self,m yop,sec1,meth1, sec2,meth2,date ):
self.myop=myop
self.sec1=sec1
self.meth1=meth 1
self.sec2=sec2
self.meth2=meth 2
self.date=date
def show(self):
print 'algday',
self.myop,self. sec1,self.meth1 ,self.sec2,self .meth2,self.dat e
def calc(self):
s1=namedayvals( self.sec1, self.date)
x1=getattr(s1,s elf.meth1)()
s2=namedayvals( self.sec2, self.date)
x2=getattr(s2,s elf.meth2)()
if self.myop=='mys um':
out=mysum(x1,x2 )
elif self.myop=='myl ess':
out=myless(x1,x 2)
elif self.myop=='myd iv':
out=mydiv(x1,x2 )
elif self.myop=='myt imes':
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,num 2):
if num1=='NA' or num2=='NA':
temp='NA'
else:
temp=num1-num2
return temp

def mytimes(num1,nu m2):
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.appen d(dict({'200804 22': (100.1,100.2,10 0.3,100.4),
'20080423': (101.1,101.2,10 1.3,101.4),
'20080424': (102.1,102.2,10 2.3,102.4)}))
namelist.append ('TEN')
valuelist.appen d(dict({'200804 22': (10.1,10.2,10.3 ,10.4),
'20080423': (11.1,11.2,11.3 ,11.4)}))

operatorlist=['mydiv','mysum' ,'myless','myti mes']
valuenames=['open','high',' low','close']
daylist=['20080422','200 80423','2008042 4']

while 1:
rop=random.choi ce(operatorlist )
rn1=random.choi ce(namelist)
rv1=random.choi ce(valuenames)
rn2=random.choi ce(namelist)
rv2=random.choi ce(valuenames)
print rop,rn1,rv1,rn2 ,rv2
calcs=[]
for date in daylist:
a=algday(rop,rn 1,rv1,rn2,rv2,d ate)
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
17076
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 special 'self' (or anything esle) argument in class method definitions. I might have missed an explanation in the docs, a quick Google search did not help. Is there somewhere on the web you could direct me to? Thanks,
4
8031
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 in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming language should support these so I'm sure that Python is no exception, but how can these be...
0
2067
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 with potential to be useful, but I would like to hear more opinions first. If this is deemed to be useful, I *may* try to write a PEP for it. This is not a promise or even a proposal, at this point. Broadly generalizing, classes in Python have...
2
2090
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. However, I need to provide bindings for an application that Python is embedded into, and thanks to Qt the bindings are going to be both simple and quite powerful. However, I need a way to do class methods...
18
6954
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 guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
6
1292
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 following error: fatal error LNK1179: invalid or corrupt file: duplicate COMDAT '??0__unnamed@@QAE@XZ' The "??0__unnamed@@QAE@XZ" symbol undecorates to "public: __thiscall __unnamed::__unnamed(void)" so I think the compiler is using the same class...
10
1647
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 certain methods if a global indicates it is okay to have those methods. So I want something like: global allow allow =
4
5306
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 virtual functions public static void doShape(Shape s)
20
1732
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 learning JavaScript and then BAM, I understood them. Just a little while ago, I had a fear of decorators because I really couldn't find a definitive source to learn them (how to with with @). How important are they? They must be important...
0
8997
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8833
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9568
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8257
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, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6079
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3320
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.