dictionary with object's method as thier items

Bruno Desthuilliers onurb at xiludom.gro
Wed Aug 30 14:15:47 EDT 2006


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 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list