gpt4 book ai didi

python - 从导入文件中的主脚本调用函数

转载 作者:行者123 更新时间:2023-11-30 22:55:57 26 4
gpt4 key购买 nike

在开始之前,我知道有很多问题听起来很像这个问题,但我的问题有点不同......所以这里是......

正如标题所示,我试图在导入的模块中调用 main.py 脚本中定义的函数。然而,这种情况与循环导入的情况有点不同。我最近用 pygame 做了很多工作,并决定制作一个包含按钮、文本、声音等类的模块。但我希望这个文件是通用的,这样它就可以与我制作的任何游戏或应用程序一起使用。按钮通常具有绘制函数之类的功能,因此我可以轻松地将这些变量传递到函数中,而不会出现问题。当我到达我想要检查按钮是否被单击以及是否执行某些操作的部分时,问题就出现了。我想对其进行设置,以便我可以传入命令的字符串参数,并对其使用 eval() 命令(python 2.7)。但是,它会抛出函数未定义的错误。我知道这是为什么,但我想看看是否可以采取任何措施来解决这个问题,以使模块尽可能保持“通用”。下面是一组基本代码,可帮助解释我想要做什么。

模块1.py

class Button(object):
def __init__(self,x=0,y=0,image=None,command=""):
self.x = x
self.y = y
self.image = image
self.command = command

"""
Image this part filled with draw commands and stuff...
These functions work perfectly fine
"""

#Now here is the issue - local is mouse position
def checkClick(self, local):
#If statments here to determine if mouse over button and
#if mouse is clicked... The part below fails
eval(self.command)

main.py

import module1
import pygame

def quitgame():
pygame.quit()
quit()

local = pygame.mouse.get_pos()
b = module1.Button(command="quitgame")

#At this point lets assume that the mouse is overtop the button and the
#following function in the button will run
b.checkClick(local)

正如我之前所说,该错误表明我尝试调用的函数未定义。我已经找到了解决方法,所以我不需要答案告诉我如何更改它,这样它就不需要命令作为输入。然而,我想这样做,以便我可以输入命令作为参数。也许我没有按照应有的方式输入命令,但我想这样做,特别是因为 tkinter 模块允许您输入命令作为输入/变量。也许没有办法像我希望的那样做到这一点,但我真的希望尽可能保持此代码的可重用性,而无需在游戏之间进行更改,而且我宁愿不必每次都将此代码放入我的游戏/应用程序中制作它们(就像我之前所说的,我给出的代码示例只是一个示例,我的实际按钮代码比我上面所做的要大得多)。正如我之前所说,我知道有很多问题与此类似,但它们对我解决这个问题没有任何帮助。其他人建议使用导入的脚本,其中包含附加变量等,但我宁愿不这样做。另外,我有一个解决方法可以完全解决这个问题,但它并不像这那么简洁或简单。

与往常一样,我们将不胜感激任何帮助,并提前感谢您的回答,以防我无法立即回复您。

最佳答案

I want to have it set up so that I can pass in a string argument for a command, and use the eval() command on it (python 2.7).

不,不,不。向其传递一个函数:

# In main.py
b = module1.Button(command=quitgame)

# In module1.py
def checkClick(self, local):
...
self.command()

eval 几乎从来都不是适合任何工作的工具。

如果您不想定义函数只是为了将其作为命令参数传递,则可以使用lambda短(单表达式)函数:

b = module1.Button(command=lambda: do_whatever(some, arguments))

关于python - 从导入文件中的主脚本调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com