开发者

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" func开发者_运维技巧tion from the dict key name
                self.key()
                ... HOW CAN I DO THIS?

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


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.


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}}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜