为什么eval()不能找到函数?

2024-06-28 19:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

def __remove_client(self, parameters):
        try:
            client = self.__client_service.remove_client_by_id(int(parameters[0]))

            FunctionsManager.add_undo_operation([self.__client_service, self.__rental_service],
                                                UndoHandler.delete_client_entry, [client[0], client[1]])
            FunctionsManager.add_redo_operation(eval('self.__add_new_client(client[0].id,client[0].name)'))

这给了我:'UI' object has no attribute '__add_new_client' 我该怎么办?或者有没有其他方法可以将该函数添加到我的repo()堆栈中,而不用在我运行时调用该函数


Tags: 函数selfclientaddidnewbydef
1条回答
网友
1楼 · 发布于 2024-06-28 19:39:41

根据Private方法的文档:

Notice that code passed to exec() or eval() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.

至于为什么你的eval()毫无意义,这是:

eval('self.__add_new_client(client[0].id,client[0].name)')

完全等同于如果您只是运行代码:

self.__add_new_client(client[0].id,client[0].name)

直接。看起来你可能希望得到某种延迟的懒惰的评估或者别的什么,但这不是它的工作原理。也许您想通过该方法的部分评估,例如:

from functools import partial
FunctionsManager.add_redo_operation(partial(self.__add_new_client, client[0].id, client[0].name))

如果这是您自己的代码,那么您不应该实际使用__方法,除非您确切地知道自己在做什么。一般来说,没有充分的理由使用这个功能(我甚至认为Guido在过去对这个功能感到遗憾)。它主要用于文档中描述的特殊情况,在这种情况下,您可能希望子类重写一个特殊的方法,并且您希望保留该方法的一个“私有”副本,该副本不能被重写

否则,只需对内部属性和方法使用单个_约定

相关问题 更多 >