简体   繁体   English

Python:在模块之间传递函数名称作为参数

[英]Python: Passing a function name as an argument between modules

Versions 版本号

Python 3.4 with Pygame 1.9.2 带有Pygame 1.9.2的Python 3.4

Question

How can I pass the name of a function/method from one module, where this function does NOT exist, to the module containing it without having to resort to making it a string and evaluating it by eval()? 如何将一个函数/方法的名称从一个不存在该函数的模块传递到包含该函数/方法的模块,而不必求助于使其成为字符串并通过eval()对其求值?

Background 背景

I have a simple MVC pattern for training purposes. 我有一个简单的MVC模式用于培训。 For simplicity's sake let's just presume we pressed a button in the menu. 为了简单起见,我们假设我们按下了菜单中的一个按钮。 Here's what happens: 这是发生了什么:

The controller sends our event, the click as ClickEvent (containing position, mouse button and if the button was pressed or released), to the currently running logic, the menu. 控制器将我们的事件(作为ClickEvent的单击)(包含位置,鼠标按钮以及是否已按下或释放按钮)发送到当前运行的逻辑菜单。 The menu then evaluates the click depending on its position and if it happened on a button, it returns a ModelEvent containing the name of a method of the model. 然后,菜单根据其位置评估单击,如果单击发生在按钮上,它将返回一个ModelEvent,其中包含模型方法的名称。 The model then receives said ModelEvent and evaluates it. 然后,模型接收所述ModelEvent并对其进行评估。 If any visible changes happen, it creates a new ViewEvent (this would go beyond my question). 如果发生任何可见的更改,它将创建一个新的ViewEvent(这超出了我的问题)。

Approaches 方法

I approached the problem in three ways so far, once by lambda (which doesn't seem to fit my needs at all or I horribly misunderstood it) and twice by using strings with eval(). 到目前为止,我以三种方式解决了这个问题,一次是通过lambda(这似乎根本无法满足我的需要,或者是我误解了它),另一次是通过将字符串与eval()一起使用。 The shortcomings of the latter approach are obvious: The name of the function has to be passed between the instances as a string and then evaluated by eval() which takes its time. 后一种方法的缺点很明显:函数名称必须在实例之间作为字符串传递,然后由eval()进行评估,这会花费时间。

What would be an efficient way to pass the names of methods and functions from one module, where they don't exist, to another, where they are to be executed, without having to use strings and eval()? 在不使用字符串和eval()的情况下,将方法和函数的名称从一个不存在的模块传递到另一个要执行的模块的有效方法是什么?

Or, if you see any grave mistakes in my general approach, I'd be glad to hear about it as I'm still learning. 或者,如果您在我的一般方法中发现任何严重错误,那么在我仍在学习的过程中,我很高兴听到它。

When I understand you correctly, you are mixing Callbacks with Events.Perhaps this makes the problem so problematic. 当我正确理解您的信息时,您就将回调与事件混在一起了。也许这使问题变得如此棘手。

In Python functions are objects, and can be passed as any other object like strings. 在Python中,函数是对象,可以作为字符串之类的任何其他对象传递。 So there is no need to pass names and evaluate them. 因此,无需传递名称并对其进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM