代码之家  ›  专栏  ›  技术社区  ›  Alfonso de la Osa

在Python中动态调用函数的方法是什么?

  •  4
  • Alfonso de la Osa  · 技术社区  · 15 年前

    我想做如下事情:

    dct = ['do_this', 'do_that']
    dct[0]() // call do_this
    

    如何在不切换和不使用lambda或函数列表的情况下实现这一点?

    显式地,我想按名称引用函数。

    8 回复  |  直到 15 年前
        1
  •  10
  •   BenMorel Manish Pradhan    11 年前

    函数是一类对象。所以像这样:

    def do_this():
        print "In do_this"
    
    def do_that():
        print "In do_that"
    
    dct = [do_this, do_that]
    dct[0]()
    

    如果您真的想从字符串列表中调用它们,可以使用globals():

    dct = ['do_this', 'do_that']
    globals()[dct[0]]()
    

    >>> import this

        2
  •  12
  •   Frédéric Hamidi    15 年前

    功能包括 first-class objects 在Python中:

    def do_this():
        pass
    
    def do_that():
        pass
    
    dct = [do_this, do_that]
    dct[0]()  # calls do_this()
    

    dct 当然必须是一个字符串列表,我同意 eval()

    eval(dct[0] + "()")
    

    不是很漂亮,但是在 globals() getattr()

        3
  •  3
  •   Zooba Necrolis    15 年前

    你可以用 getattr 如果它们在模块中或 globals()

    dct = ['do_this', 'do_that']
    
    getattr(my_module, dct[0])()
    
    globals()[dct[0]]()
    
        4
  •  1
  •   joni    15 年前

    如果要调用的函数是模块的一部分:

    import module
    getattr(module, funcname_string)(*args, **kwargs)
    
        5
  •  1
  •   nmichaels    15 年前

    eval() (不流行)或使用 globals()

        6
  •  1
  •   knitti freethinker    15 年前

    在某个dict、类或实例中具有这些功能

    
    def fn_a():
        pass
    
    some_dict = {
        'fn_a': fn_a,
    }
    
    class Someclass(object):
    
      @classmethod
      def fn_a(cls):
        pass
    
      # normal instance method
      def fn_b(self):
        pass
    
    some_instance = Someclass()

    你可以: some_dict['name']() getattr(some_instance, 'fn_b')() getattr(Someclass, 'fn_a')()

        7
  •  1
  •   Roger Pate Roger Pate    15 年前
    def do_this(): pass
    def do_that(): pass
    
    dct = dict((x.__name__, x) for x in [do_this, do_that])
    # dct maps function names to the function objects
    # the names *don't* have to match the function name in your source:
    #   dct = {"foo": do_this}
    # which means user-facing names can be anything you want
    
    dct["do_this"]()  # call do_this
    
        8
  •  0
  •   Kent Wong    6 年前

    使用 getattrs()

    dct = ['do_this', 'do_that']
    
    
    getattr(class_object, dct[0])()
    

    inspect.getmembers(my_class, predicate=inspect.ismethod)
    

    然后执行for循环并调用 getattr(class, methodname)

    我认为使用getattr比使用globals()更适合大多数情况。

        9
  •  0
  •   mangalbhaskar    6 年前

    要动态调用在同一模块中定义的函数,可以这样做:

    import sys
    
    ## get the reference to the current module - key trick to get the ref to same module
    this = sys.modules[__name__]
    
    def foo():
      msg="I'm called dynamically!"
      return msg
    
    ## `fname` can be taken as an input from the user
    fname='foo'
    
    ## get the reference to the function from the module
    fn = getattr(this, fname)
    
    ## make the function call
    fn()