我正在try 使用神奇的python partialmethod
functool.但此分部方法必须引用父类中的函数.
from functools import partialmethod
class MyResource:
@staticmethod
def load_resource(id):
print(f"Loding a new resource ! {id}")
return MyResource(id)
class CachedDataMixin:
_cache = {}
def _get_resource(self, source_cls, id):
if source_cls not in self._cache or id not in self._cache[source_cls]:
resource = source_cls.load_resource(id)
self._cache.setdefault(source_cls, {})[id] = resource
return self._cache[source_cls][id]
class MyClass(CachedDataMixin):
_get_my_resource = partialmethod(_get_resource, MyResource)
def run(self):
obj1 = _get_my_resource(12345)
obj2 = _get_my_resource(12345)
return obj1, obj2
MyClass().run()
当我试图运行这段代码时,我在_get_my_resource = partialmethod(_get_resource, MyResource)
上收到一条错误消息NameError: name '_get_resource' is not defined
.
我试着用partialmethod(self._get_resource, MyResource)
或partialmethod(super()._get_resource, MyResource)
,但都没用.
我找到了一个将_get_resource
函数重新定义为MyClass
的解决方案,但这个解决方案对我来说似乎很难看:
class MyClass(CachedDataMixin):
def _wrapped_get_resource(self, source_cls, id):
return super()._get_resource(source_cls, id)
_get_my_resource = partialmethod(_wrapped_get_resource, MyResource)
...
有没有人有一个很好的解决方案,可以不写我难看的变通方法?