是否可以动态生成彼此非常相似的类方法?
假设我有一堂这样的课:
class KitchenDrawer:
def _check_if_tool_available(self, tool) -> bool:
# check if "tool" is in the drawer
def is_knife_available(self) -> bool:
return self._check_if_tool_available("knife")
def is_spoon_available(self) -> bool:
return self._check_if_tool_available("spoon")
def is_fork_available(self) -> bool:
return self._check_if_tool_available("fork")
有没有办法动态生成
is_knife_available()
、is_spoon_available()
、is_fork_available()
,这样就没有那么多重复代码了?
(你们中的一些人可能会建议简单地将
_check_if_tool_available(self, tool)
作为一种面向公众的方法并继续我的生活。公平。但除了明智的解决方案之外,我对这里的具体问题感兴趣。)
谢谢!
是的,这是可能的,但它可能是难以调试的方法。您可以使用
setattr()
来实现此目的。
例如,你可以像这样实现:
class KitchenDrawer:
def _check_tool(self, tool):
return tool in ['knife', 'spoon', 'fork']
for tool in ['knife', 'spoon', 'fork']:
setattr(KitchenDrawer, f'is_{tool}_available', lambda self, t=tool: self._check_tool(t))
# Usage
drawer = KitchenDrawer()
print(drawer.is_knife_available()) # True
您还可以检查方法
is_fork_available
、is_knife_available
、is_spoon_available
在类中可用:
dir(KitchenDrawer)
# [... 'is_fork_available', 'is_knife_available', 'is_spoon_available']