我对 OOP 很陌生,所以这可能是一个非常愚蠢的问题。
我有许多类,它们都使用一个通用对话框,该对话框在我的实用程序模块中执行一个简单的“获取文件”。将 wx 传递给该函数以便我不必在 utils.py 文件顶部添加“import wx”是一种不好的做法吗?
目前,我通过单击按钮并传递默认路径来调用例程,但这意味着我必须在 utils.py 和 test.py 中包含“import wx”
测试.py
import utils, wx
#... Lots of wx stuff happens here
f = utils.get_file(self, def_path)
#... Lots more wx stuff happens here
utils.py
import wx
def get_file(self,defaultPath):
newFile = ''
with wx.FileDialog(self, "Select sound file",
style=wx.FD_OPEN, defaultDir=defaultPath) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return newFile # the user changed their mind
# Proceed loading the file chosen by the user
newDir = fileDialog.GetDirectory()
if newDir == defaultPath:
newFile = fileDialog.GetFilename()
else:
newFile = fileDialog.GetPath()
return newFile
那么,将调用更改为
f = utils.get_file(self, wx, def_path)
和函数
def get_file(self, wx, defaultPath):
这允许我从 utils.py 中删除“import wx”
最佳答案
将函数解耦到不同的文件中会更干净。这样你就只处理返回值。假设以下两个文件位于同一文件夹中:
file_one.py
import random
def get_a_number():
return random.randint(0, 101)
file_two.py
from file_one import get_a_number
def multiply_random_number(random_number, multiple):
print(random_number * multiple)
multiply_random_number(get_a_number(), 4)
请注意我如何不在 file_two 中再次导入 random。我只向我调用的函数提供来自 file_one 的第一个位置参数,即它的返回值。
关于python - 将 wx 从类传递给函数是好是坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635661/