【发布时间】: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