是 good/bad 将 wx 从 class 传递给函数吗?
Is it good/bad to pass wx from a class to a function?
我对 OOP 很陌生,所以这可能是一个非常愚蠢的问题。
我有很多 类,它们都使用一个通用对话框,该对话框在我的实用程序模块中执行一个简单的 "get file"。将 wx 传递给该函数是否是一种不好的做法,这样我就不必在 utils.py 文件的顶部添加 "import wx"?
目前我通过单击按钮并传递默认路径来调用例程,但这意味着我必须在 utils.py 和 test.py 中包含 "import wx"
test.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"
将您的函数分离到不同的文件中会更清晰。这样你只处理 return 值。假设以下两个文件在同一文件夹中:
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 中如何不再随机导入。我只给函数我在那里调用 file_one 的第一个位置参数,这是 return 值。
我对 OOP 很陌生,所以这可能是一个非常愚蠢的问题。
我有很多 类,它们都使用一个通用对话框,该对话框在我的实用程序模块中执行一个简单的 "get file"。将 wx 传递给该函数是否是一种不好的做法,这样我就不必在 utils.py 文件的顶部添加 "import wx"?
目前我通过单击按钮并传递默认路径来调用例程,但这意味着我必须在 utils.py 和 test.py 中包含 "import wx"
test.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
将您的函数分离到不同的文件中会更清晰。这样你只处理 return 值。假设以下两个文件在同一文件夹中:
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 中如何不再随机导入。我只给函数我在那里调用 file_one 的第一个位置参数,这是 return 值。