python - 将 wx 从类传递给函数是好是坏?

标签 python wxpython parameter-passing

我对 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/

相关文章:

python - 随着 Lua 和 Python 的嵌入,是否还有 Basic 的一席之地?

c - 如何在此示例中实现数组

java - 将 Java 引用传递到对象链的最佳方式

python - 在 python (JES) 中给函数一个操作

python - 在 Django 中结合 ~Q 和 F?

python - queue.empty 并在空的时候做一个 put

python - PyLucene 索引器和检索器示例

Python 和 Matplotlib 以及鼠标悬停注释

python - 如何在 wxPython 中制作一个简单的文件浏览器?

python - 如何一次性删除 agw.aui.notebook 的所有页面?