简体   繁体   English

Python 哪种方法最好 - “任务对象列表”或“具有可变元素列表的类任务”

[英]Python what approach is the best - "list of Task objects" or "class Tasks with variable list of elements"

I want to implement a list of tasks, but I don't know which approach of the two is the best:我想实现一个任务列表,但我不知道这两种方法中哪种方法最好:

First:第一的:

class Tasks(object):

    def __init__(self) -> None:
        self.tasks = []

    def add(self, process, instance) -> None:
        self.tasks.append((process, instance, Result()))

# example usage:
tasks = Tasks()
tasks.add('process-1', 'instance-1')

or maybe:或者可能:

class Task(object):

    def __init__(self, process, instance) -> None:
        self.process = process
        self.instance = instance
        self.result = Result()

# example usage:
tasks = []
task = Task('process-1', 'instance-1')
tasks.append(task)

The goal is to keep somewhere processes and their results when doing parallel tasks (multiprocessing library).目标是在执行并行任务时将进程及其结果保留在某个地方(多处理库)。 Maybe some way is more pythonic?也许某种方式更pythonic? or just more OOP.或者更多 OOP。

Highly opinionated, and probably more suited for Software Engineering SE , but each has its own advantages and disadvantages.固执己见,可能更适合软件工程 SE ,但各有优缺点。

The first one is supposedly easier to use and a more "OOP" fashion, but I dislike it for various reasons: It restricts your containers to that specific task list, it's harder to extend, and you lose a lot of built-in list operations when using that structure (if you don't inherit from collections.abc.MutableSequence ).第一个应该更容易使用并且更“OOP”时尚,但我不喜欢它有多种原因:它限制你的容器到那个特定的任务列表,它更难扩展,你失去了很多内置的列表操作使用该结构时(如果您不继承自collections.abc.MutableSequence )。

The second one is more akin to anemic object model. Some consider this to be an anti-pattern but I find numerous advantages in this approach here:第二个更类似于贫血 object model。有些人认为这是一种反模式,但我发现这种方法有很多优点:

  1. You have the builtin list capabilities.您具有内置列表功能。
  2. Your task object is simple and can be extended / subclassed.您的任务 object 很简单,可以扩展/子类化。
  3. You can easily switch the container (set, list, tuple...).您可以轻松切换容器(集合、列表、元组...)。
  4. Easier to handle multi-threading and multi-processing when the container object does not need to guard against such concurrent operations.当容器 object 不需要防范此类并发操作时,更容易处理多线程和多处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM