Python 中的编码结构

Coding Structure in Python

这个问题主要涉及像我这样的整体编码新手。我最近开始从教科书和各种在线资源中学习 python,因为这基本上是我的第一门编程语言,也是我第一次接触编码,所以我很难理解如何将一般结构合并到我的脚本中。

目前我正在编写代码,将数据文件的各个部分解析为单独的列表(据我所知是 reader),然后是允许我进行用户确定的更改的代码说列表,最后是将新列表写入文件的代码。最终目标是拥有允许我 add/remove 特定数据值并生成具有确定更改的新数据文件的代码。

到现在,写代码本身并没有特别难读编辑写文件,只是不知道各种函数应该怎么写才算"neat and organized"。因为我在实际做这个小项目的同时也在学习这门语言,所以我不熟悉许多我认为是标准代码结构的东西。

一般来说,对于这样的项目,我应该将其全部写在一个由单独的 classes/functions 组成的脚本中吗?编写单独的模块将 return 值从一个模块导入另一个模块是否更好?一个模块通常会有多个 class 吗?从一种鸟瞰图的方法来构建代码,最好的方法是什么?目前我的代码没有实际的结构,所有内容都是在任何 main() classes 和函数之外写的,它只是 运行s 给定一个特定的输入文件,但我很确定这一点可能不是编写代码的正确方法。对于这种初学者问题,我深表歉意,但我在编写这段代码的过程中一直在学习,还没有 运行 进入我的文本的任何部分来构建脚本本身。

我不确定 SO 是否是最好的询问地点。但是,对我有帮助的一件事是为可管理的逻辑块创建不同的函数。您提到您的所有代码都是在没有任何结构的情况下编写的。

很棒的是您已经提到了逻辑分离。尝试拥有基于该逻辑的单一作业的功能。例如:

-- "parse out various sections of a data file into separate lists"

def parse_data_file(full_file_path):
    raw_data = read_file(full_file_path) # delegate this out to another function if you're feeling like you need more separation
    data_lists = generate_sub_lists(raw_data) # delegate
    return data_lists

-- "will allow me to make user-determined alterations to said lists"

def edit_lists(user_commands_kv_args, data_lists):
    for type_of_command, command in user_commands_kv_args:
        if type_of_command == 'Delete':
            run_command_on_lists(command='Delete', data_lists)

-- "a code for writing the new lists to a file"

def write_lists_to_file(data_lists, output_file_full_path):
    with open(output_file_full_path, 'w+') as f:
        for ls in data_lists:
            f.writelines(ls)

至少现在您可以根据功能进行一些分离。稍后您甚至可以根据操作类型创建单独的 classes。例如:

class DataParser():
    def __init__(full_file_path):
        self.file_path = full_file_path

    def read_from_sql():
        pass

    def read_from_mongo():
        pass

    def read_from_txt():
        pass

这样做的好处是,如果您的文件格式或源代码发生变化,您只需调整 class 接口来解析该数据,而不用遍历整个主入口点代码。希望对您有所帮助。