按需执行存储在变量中的class函数
Execute class function stored in variable on demand
我有两个 classes 具有以下功能:
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 可以在一个对象上调用一个函数,由另一个函数动态获取,都存储在一个变量中并且在调用某个函数时全部执行:
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
您应该将 base
传递给 run
而不是乱用 global
。 base
没有 fetch
方法,因此您必须使用 base
作为参数调用作为属性的 fetch
函数。然后,您可以将该调用的 return 值发送到 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
我有两个 classes 具有以下功能:
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 可以在一个对象上调用一个函数,由另一个函数动态获取,都存储在一个变量中并且在调用某个函数时全部执行:
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
您应该将 base
传递给 run
而不是乱用 global
。 base
没有 fetch
方法,因此您必须使用 base
作为参数调用作为属性的 fetch
函数。然后,您可以将该调用的 return 值发送到 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