【发布时间】:2020-05-11 07:08:06
【问题描述】:
我有一个类似于以下的课程:
from joblib import Memory
import time
def find_static_methods(cls):
# to be implemented
pass
class A:
def __init__(self, cache_path: str):
self._memory = Memory(cache_path, verbose=0)
self._methods = {}
for name, method in find_static_methods(A):
self._methods[name] = self._memory.cache(method)
def __getattribute__(self, item):
if item in self._methods:
return self._methods[item]
return super(A, self).__getattribute__(item)
@staticmethod
def method1(a: int, b: int):
time.sleep(3)
return a + b
我正在尝试使用 joblib.Memory 来记忆 method1。但我事先不知道cache_path。请帮助我在这里实现find_static_methods。
【问题讨论】:
-
你关心潜在的继承方法吗?
-
无论如何,如果你不关心继承的方法,所有的静态方法都会类似于
[attr for attr in vars(A).values() if isinstance(attr, staticmethod)]。如果这样做,则必须按方法解析顺序检查所有类的属性。 -
谢谢让我试试这个!
-
我也不确定
Memory.cache是否可以与staticmethod对象一起使用,您可能必须使用底层函数,可在attr.__func__获得 -
我正要问同样的问题,因为我从 joblib 收到一个错误,说
staticmethod对象不可调用。
标签: python python-3.x memoization joblib