473,382 Members | 1,658 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,382 software developers and data experts.

dictionary with object's method as thier items

Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
etc..
thanks

Aug 30 '06 #1
7 2047
On 30 Aug 2006 06:35:17 -0700
"noro" <am******@gmail.comwrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
etc..

Sure. But the syntax would be:
d['function one'] = c.func1
d['function one']()

I'm not sure what this gets you but it works.

John Purser

Aug 30 '06 #2
noro wrote:
Is it possible to do the following:

for a certain class:
[...]
by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C
Something like this?
>>class C:
.... def f1(self):
.... print "i'm one"
.... def f2(self):
.... print "i'm two"
....
>>obj = C()
d = {'one': obj.f1, 'two': obj.f2}
d['one']()
i'm one
>>d['two']()
i'm two

--
Roberto Bonvallet
Aug 30 '06 #3
noro wrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
etc..
Let me guess... What you want to is in fact to call a method by it's
name ? If so, getattr(obj, name) is your friend:

class Knight(object):
def __init__(self):
self._saywhat = "ni"
self._wantwhat ="shrubbery"

def says(self):
return self._saywhat

def wants(self):
return self._wantwhat

k = Knight()

print getattr(k, "says")()
print getattr(k, "wants")()

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #4
noro wrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}
Perhaps this:
>>class C:
.... def function(self, arg):
.... print arg
....
>>obj = C()
d = C.__dict__
d['function'](obj, 42)
42
>>>

Georg
Aug 30 '06 #5
At Wednesday 30/8/2006 10:35, noro wrote:
>for a certain class:
by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
You can use dir(obj) to get its list of attributes (including method
names) then use getattr to invoke the method.

methodname='func1'
getattr(obj,methodname)()

See the inspect module too.
Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 30 '06 #6
great that is what i looked for.
>>class C:
... def function(self, arg):
... print arg
...
>>obj = C()
>>d = C.__dict__
>>d['function'](obj, 42)
42
this allows me the access the same method in a range of objects.

i can put all the functions i need in a dictionary as items, and the
vars as keys, and then call them for all objects that belong to a
class..

something like this

----------------------------------------------------
class C:

#object vars
self.my_voice
self.my_size
self.my_feel

# a method that do somthing, that might give different result for
different objects
getVoice(self):
return(self.my_voice+'WOW')

getSize(self):
return(self.my_size*100)

getFeel(self):
return(self.my_feel)
#create the dictionary with a reference to the class methode
dic={'voice':C.getVoice,'size':C.getSize,'feel':C. getFeel}
# create array of 10 different objects
cArray = []
for i in range(10)
cArray.append(C())
cArray[0].my_size=i

# choose the function you need, and get the result
choice=WHAT EVER KEY (e.g 'size')
for i in range(10)
print dic[choice](cArray[i])

#or even print all the values of all objects. if i ever want to print
diffenet valuse i only need
# to change the dictionary, nothing else...
for choice in dic:
for i in range(10)
print dic[choice](cArray[i])
---------------------------------------------------------------
i totaly forget about the "self" argument in every method...

a. is the main reason "self is there, or is it only a side effect?
b. what do you think about this code style? it is not very OOP, but i
cant see how one can do it other wise, and be able to control the
function printed out with something as easy as dictionary..

Georg Brandl wrote:
noro wrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

Perhaps this:
>>class C:
... def function(self, arg):
... print arg
...
>>obj = C()
>>d = C.__dict__
>>d['function'](obj, 42)
42
>>>


Georg
Aug 30 '06 #7
noro wrote:
great that is what i looked for.
Hmmm... Not quite sure
>>>class C:
... def function(self, arg):
... print arg
...
> >>obj = C()
d = C.__dict__
d['function'](obj, 42)
42

this allows me the access the same method in a range of objects.
class Obj(object):
def __init__(self, num):
self.num = num
def method(self):
return "in %s.method" % self

for obj in [Obj(i) for i in range(10)]:
print getattr(obj, "method")()

i can put all the functions i need in a dictionary as items, and the
vars as keys, and then call them for all objects that belong to a
class..

something like this

----------------------------------------------------
class C:

#object vars
self.my_voice
self.my_size
self.my_feel

# a method that do somthing, that might give different result for
different objects
getVoice(self):
return(self.my_voice+'WOW')

getSize(self):
return(self.my_size*100)

getFeel(self):
return(self.my_feel)
#create the dictionary with a reference to the class methode
dic={'voice':C.getVoice,'size':C.getSize,'feel':C. getFeel}
# create array of 10 different objects
cArray = []
for i in range(10)
cArray.append(C())
cArray[0].my_size=i

# choose the function you need, and get the result
choice=WHAT EVER KEY (e.g 'size')
for i in range(10)
print dic[choice](cArray[i])

#or even print all the values of all objects. if i ever want to print
diffenet valuse i only need
# to change the dictionary, nothing else...
for choice in dic:
for i in range(10)
print dic[choice](cArray[i])
---------------------------------------------------------------
i totaly forget about the "self" argument in every method...
???
a. is the main reason "self is there, or is it only a side effect?
I'm not sure I understand your question.
b. what do you think about this code style?
Don't ask me if you don't want to get hurt !-)
it is not very OOP,
This is not a problem - Python doesn't forces you that much into OO.
but i
cant see how one can do it other wise,
using getattr(<object>, <attrname>[,<default>])
and be able to control the
function printed out with something as easy as dictionary..
Here's a somewhat more pythonic way to do the same thing (NB : not tested):

# a simple decorator
def choice(func):
func.is_choice = True
return func

# helper func
def is_choice(obj):
return callable(obj) and getattr(obj, 'is_choice', False)

# braindead metaclass
class ChoicesMeta(type):
def __init__(cls, name, bases, classdict):
cls.choices = [name for name, attrib in classdict.items() \
if is_choice(attrib)]

# our class...
class Foo(object):
__metaclass__ = ChoicesMeta

def __init__(self, num):
self.num = num

# mark the method as usable in choices
@choice
def bar(self):
return "foo #%s.bar" % self.num

@choice
def baaz(self):
return "foo #%s.baaz" % self.num

# let's test:
foos = [Foo(i) for i in range(10)]

choice = <whatever name existing in Foo.choices>
for foo in foos:
print getattr(foo, choice)()
HTH

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #8

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

Similar topics

1
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148...
4
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I...
1
by: greg | last post by:
Hi I referenced in COM Dictionary object (like Scripting Dictionary) It has Items method that returns object What should I cast it to??? some collection? Ideas? SRSPLUSLib.SrsClass srs = new...
2
by: jg | last post by:
I was trying to get custom dictionary class that can store generic or string; So I started with the example given by the visual studio 2005 c# online help for simpledictionay object That seem...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
3
by: Mark Rae | last post by:
Hi, Is it possible to use a Dictionary<int, stringor even Dictionary<string, stringas the DataSource for a DropDownList directly, i.e. without having to iterate through the the Dictionary's...
5
by: Bill Jackson | last post by:
What is the benefit of clearing a dictionary, when you can just reassign it as empty? Similarly, suppose I generate a new dictionary b, and need to have it accessible from a. What is the best...
5
by: davenet | last post by:
Hi, I'm new to Python and working on a school assignment. I have setup a dictionary where the keys point to an object. Each object has two member variables. I need to find the smallest value...
3
by: mk | last post by:
Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): .... return "f2 " + arg .......
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...

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.