pkdkk
pkdkk

Reputation: 3971

Dict key as function in a class

How do I call the get_productname function from the dictionary in the code below?

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         }
    }

class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                ... here i want to call the "get_productname" function from the dict key name
                self.key()
                ... HOW CAN I DO THIS?

    def get_productname(self, id):
        ...
        return productname 

Upvotes: 2

Views: 2604

Answers (4)

Tim Alexander
Tim Alexander

Reputation: 114

Even though people might flame me for suggesting this:

http://docs.python.org/library/functions.html#eval

Try this:

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         }
    }

class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                eval("self.%s()" % key)
                # or, if you want to pass ID as an arg:
                eval("self.%(method_name)s(id=%(id)s)" % \
                      dict(method_name=key, id=value["id"])

    def get_productname(self, id):
        ...
        return productname 

Haven't run it, but that should work.

Upvotes: 0

martineau
martineau

Reputation: 123531

Assuming you have a get_productname() function defined somewhere, I'd just add it to the dictionary like this:

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         'func' : get_productname
                         }
    }

Then you could call it like this:

class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                # then call the associated function like this
                test[key]['func']()
                ...

Hope that helps.

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 602735

If you know in advance what classes the methods you want to call belong to, you could use the methods itself instead of their names as dictionary keys. Then you can simply call them:

class search(object):
    def __init__(self, test):
        for func, value in test.iteritems():
            if value['active']:
                func(self, value['id'])
    def get_productname(self, id):
        pass

test = {search.get_productname: {'id' : 1, 'active' : 1}}

Upvotes: 3

g.d.d.c
g.d.d.c

Reputation: 48048

You want the getattr function.

class search(object):
  def __init__(self):
    for key, value in test.items():
      if test[key]['active']:
        getattr(self, key)(test['key']['id'])

Per the comments, if you're not 100% positive that the method will exist you can perform a hasattr(self, name) check ahead of time, but it's equivalent to this:

try:
  getattr(self, key)
except AttributeError, e:
  # code here that would handle a missing method.

Upvotes: 8

Related Questions