How to Generate Functions Dynamically in Python

  Kiến thức lập trình

Is it possible to generate dynamically class methods which are very similar one another?

Say I have a class like this one:

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(self, "knife")

    def is_spoon_available(self) -> bool
        return self._check_if_tool_available(self, "spoon")

    def is_fork_available(self) -> bool
        return self._check_if_tool_available(self, "fork")

Is there a way to generate is_knife_available(), is_spoon_available(), is_fork_available() dynamically, so there is not so much repeated code?

(Some of you might suggest to simply make _check_if_tool_available(self, tool) a public facing method and carry on with my life. Fair. But more than the sensible solution, I am interested in the nitty gritty issue here.)

Thanks!

LEAVE A COMMENT