简体   繁体   中英

Python: Passing a function name as an argument between modules

Versions

Python 3.4 with Pygame 1.9.2

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()?

Background

I have a simple MVC pattern for training purposes. 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. 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. The model then receives said ModelEvent and evaluates it. If any visible changes happen, it creates a new ViewEvent (this would go beyond my question).

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(). 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.

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()?

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. So there is no need to pass names and evaluate them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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