dictionary with object's method as thier items

N

noro

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
 
R

Roberto Bonvallet

noro said:
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?
.... 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
 
J

John Purser

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
 
B

Bruno Desthuilliers

noro said:
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
 
G

Georg Brandl

noro said:
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:
.... def function(self, arg):
.... print arg
....
>>> obj = C()
>>> d = C.__dict__
>>> d['function'](obj, 42) 42
>>>


Georg
 
G

Gabriel Genellina

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
 
N

noro

great that is what i looked for.
... 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)

#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 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 said:
noro said:
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:
... def function(self, arg):
... print arg
...
obj = C()
d = C.__dict__
d['function'](obj, 42) 42


Georg
 
B

Bruno Desthuilliers

noro said:
great that is what i looked for.

Hmmm... Not quite sure
... 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)

#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 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,

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top