Python类 - 被覆盖的实例?

soc*_*rve 2 python

当我为我创建的类调用一个对象的新实例时,我的一个类实例就被覆盖了.为什么会这样?示例如下.

我的课程定义如下:

class my_class:
    attribute = ""
    examples = [] 
    children = []
    d = {}
    def __init__(self, attribute, e):
        self.attribute = attribute
        self.examples = e

        for ex in self.examples:
            self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1
Run Code Online (Sandbox Code Playgroud)

我正在制作一个初始实例:

root = my_class(some_attribute, data)
Run Code Online (Sandbox Code Playgroud)

然后,我创建另一个实例:

child = my_class(different_attribute, root.examples[somewhere_1:somewhere_2])
Run Code Online (Sandbox Code Playgroud)

最后,我的初始"root"现在与"child"在某种程度上相同,其中"root"应该保持不变.为什么是这样!?

Sin*_*ion 6

我不认为你用的初始化做attribute,examples,childrend你认为你在做什么.这些现在是类的属性,而不是每个实例的属性.如果你想在类的每个实例有它自己的属性为attribute,examples,childrend,则应该写:

class my_class:
    def __init__(self, attribute, e):

        self.attribute = attribute
        self.examples = e
        self.children = []
        self.d = {}

        for ex in self.examples:
            self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1
Run Code Online (Sandbox Code Playgroud)