【问题标题】:Execute class function stored in variable on demand按需执行存储在变量中的类函数
【发布时间】:2018-12-17 05:20:57
【问题描述】:

我有两个带函数的类:

from functools import partial

class A:
  def __init__(self, collection):
    self.collection = collection

  def filter(self, val):
    for element in self.collection:
      if element.var == val:
        return element

class B:
  def __init__(self, var):
    self.var = var

  def test(self):
    print('Element with variable ', self.var)

现在我想要一个类,它可以调用对象上的函数,由另一个函数动态获取,都存储在变量中,并且在调用某个函数时全部执行:

class C:
  def __init__(self, fetch, function):
    self.fetch = fetch
    self.function = function

  def run(self):
    global base
    # -----
    # This is the code I need
    base.fetch().function()
    # ... and currently it's completely wrong
    # -----

c = C(partial(A.filter, 5), B.test)

base = A([B(3), B(5), B(8)])

c.run()

应该打印:Element with variable 5

【问题讨论】:

    标签: python python-3.x function class functools


    【解决方案1】:

    您应该将base 传递给run,而不是与global 混淆。 base 没有 fetch 方法,因此您必须调用 fetch 函数作为属性,并将 base 作为参数。然后,您可以将该调用的返回值发送到 function

    您还将partial 应用于A.filter 略有错误。位置参数按顺序应用,因此partial(A.filter, 5) 将尝试将5 绑定到self,这将把所有东西都扔掉。相反,我们需要给它一个我们希望将5绑定到的参数的名称。

    class C:
        def __init__(self, fetch, function):
            self.fetch = fetch
            self.function = function
        def run(self, a):
            return self.function(self.fetch(a))
    
    c = C(partial(A.filter, val=5), B.test)
    c.run(A([B(3), B(5), B(8)]))
    # Element with variable  5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2015-03-26
      相关资源
      最近更新 更多