在python中获取类的所有实例

时间:2017-11-22 16:36:48

标签: python-3.x class object instance

这是我files.py文件中的课程:

class Files():

    def __init__(self, *, kwargs1=None, ......, kwargsx=None):
        self.kwargs1 = kwargs1
        ...................
        ...................
        ...................
        self.kwargsx = kwargsx

        __validate()
        if self.kwargs1 == "create":
            self.__create()
        if kwargsx == "remove":
            self.__remove()

    def __validate():
        validate attributes of object and raise execption if fails

    def __create(self):
        create file

    def __remove(self):
        remove file

在另一个文件tasks.py中我有这个:

from files import File

File(kwargs1="create", kwargs2="path/to/destination1", kwargs3="/path/to/source1",..........)
File(kwargs1="create", kwargs2="path/to/destination2", kwargs3="/path/to/source2",..........)

目前的情况是每个对象都经过验证,然后继续__create()__remove()。我问的是,是否可以先验证所有对象,然后继续。 我可以在tasks.py中实现它。我必须将私有方法__create()__remove()声明为公共方法create(self)remove(self),并且类看起来像这样:

class Files():

    def __init__(self, *, kwargs1=None, ......, kwargsx=None):
        self.kwargs1 = kwargs1
        ...................
        ...................
        ...................
        self.kwargsx = kwargsx

        __validate()

    def __validate():
        validate attributes of object and raise execption if fails

    def create(self):
        create file

    def remove(self):
        remove file

tasks.py

files = []
try:
    files.append(File(kwargs1="create", kwargs2="path/to/destination1", kwargs3="/path/to/source1",..........))
    files.append(File(kwargs1="create", kwargs2="path/to/destination2", kwargs3="/path/to/source2",..........))
except ValueError as e:
    print(e)
else:
    for item in files:
        if item.kwargsx == "create":
            create(item)
        elif item.kwargsx == "remove":
            remove(item)

我的问题是,是否可以在类File本身中实现此逻辑?我能想到的唯一方法是检查堆栈并迭代每个对象的初始化,但我不知道它是否会起作用!

1 个答案:

答案 0 :(得分:0)

这是一个通用方案 - 类没有对实例的引用,

dec

然后在代码中的某个地方

class File:
    _instances = []
    def __init__(self, ..., action=None):
        ....
        self.action = action
        File._instances.append(self)

    @classmethod
    def resolve_actions(cls):
        for instance in cls._instances:
            if instance.action == "create":
                instance.__create()
            elif instance.action == "remove":
                instance.__remove()