是否使用合理的类来存储多个功能所需的变量?

我正在编写python脚本,它的功能之一应该是将其自动添加到Windows启动文件夹中。

现在,我编写了一些可以为我完成此任务的函数,但是它们都依赖于多个变量,这些变量在初始分配后不应更改。但是我不确定在哪里存储它们。

这是代码段:

def write_shortcut():
    autostart_folder = winshell.startup()
    path = os.path.abspath(__file__)
    target_folder = autostart_folder + r"\proxy-changer.lnk"
    working_directory = path.replace(r'\proxy-changer.pyw','')

    with winshell.shortcut() as shortcut:
        shortcut.path = path
        shortcut.working_directory = working_directory
        shortcut.description = "Shortcut to the proxy-changer script"
        shortcut.write(target_folder)

def del_shortcut():
    os.remove(target_folder)

def check_shortcut():
    if (config.getboolean('DEFAULT','RunOnStartup') == 1 and not
        os.path.islink(target_folder)):
        write_shortcut()
    elif (config.getboolean('DEFAULT','RunOnStartup') == 0 and
          os.path.islink(target_folder)):
        del_shortcut()
    else:
        pass

第2行到第5行是我正在谈论的变量。 当前,它们处于第一个功能中,但是其他功能则无法访问它们。现在,我知道存在类,并且该类中的所有方法都可以访问该类中的变量,但是我不确定这是否正确,因为它只会包含一个对象,而不是多个对象。

在功能之外,甚至在定义它们之前,它们看起来也不是很干净。而且我不确定是否要使其全球化。

我想我一般理解课程,但不是全部,所以,如果很明显地知道上课是正确的方法,那么对不起。我只是听说经常在不需要(Stop writing classes!)的时候使用类,所以我试图避免犯同样的错误。 我是python初学者,请随时批评我的代码风格,或者告诉我我错了/可以改进它。

谢谢。

hg999520 回答:是否使用合理的类来存储多个功能所需的变量?

将常量作为模块/脚本的全局变量是完全可以的。请注意,对常量使用UPPER_CASE名称是习惯用法。

  

常量 PEP8

     

常量通常在模块级别定义并编写   在所有大写字母中都用下划线分隔单词。例子   包括MAX_OVERFLOW和TOTAL。

例如,您将在函数之前定义常量:

PATH = os.path.abspath(__file__)
TARGET_FOLDER = winshell.startup() + r"\proxy-changer.lnk"
WORKING_DIRECTORY = os.path.dirname(PATH)

def write_shortcut():
    with winshell.shortcut() as shortcut:
        shortcut.path = PATH
        shortcut.working_directory = WORKING_DIRECTORY
        shortcut.description = "Shortcut to the proxy-changer script"
        shortcut.write(TARGET_FOLDER)

def del_shortcut():
    os.remove(TARGET_FOLDER)

使用课程不会给您带来任何好处。缺点是它掩盖了您的意图,通常速度较慢,并且无法提供通常与类相关的功能。

最直接的方法是将常量添加为类属性:

class Constants:
    path = os.path.abspath(__file__)
    target_folder = winshell.startup() + r"\proxy-changer.lnk"
    working_directory = os.path.dirname(path)

def del_shortcut():
    os.remove(Constants.target_folder)

请注意,Constants的行为与带有全局变量的模块完全一样,只是它仍然具有类现在所有无用的功能。例如,尽管Constants可以实例化,但这完全没有意义,因为实例既没有状态也没有方法。

本文链接:https://www.f2er.com/3152170.html

大家都在问