【发布时间】:2022-06-11 19:51:50
【问题描述】:
我正在尝试使用神奇的 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)
...
有没有人有一个很好的解决方案来不写我丑陋的解决方法? 非常感谢您的帮助
【问题讨论】:
标签: python