首页 > 解决方案 > 生成的类在 Python 上有冲突

问题描述

我将立即从代码开始。我有两节课

class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)
        self.__keys__ = list(entries.keys())

    def __iter__(self):
        for i in self.__keys__:
            yield self.__dict__.get(i)

    def __len__(self):
        return len(self.__keys__)

    def __getitem__(self, item):
        if item in self.__keys__:
            return self.__dict__.get(item)
        else:
            return None

    def add(self, **entries):
        for key, value in entries.items():
            if key not in self.__keys__:
                self.__keys__.append(key)
            self.__dict__[key] = value

    @staticmethod
    def from_struct(struct: 'Struct'):
        return Struct(**struct.dict())

    def dict(self):
        return {key: self.__dict__.get(key) for key in self.__keys__}

class StructList:

    def __init__(self, structlist: list[Struct] = []):
        self.structlist = structlist

    def append(self, struct: Struct):
        self.structlist.append(struct)

    def __iter__(self):
        for struct in self.structlist:
            yield struct

Struct这是和的基本类StructList。这些类用于生成一些子类,但我发现了一些我还不明白的问题。如果我生成一些Struct对象,它们工作得很好:

x = Functional.Struct(a="1", b=2)
y = Functional.Struct.from_struct(x)
y.a = 12
y.add(c=12)
y.add(**{"d": 14})
z = Functional.Struct(**{"c":"1", "d":2})

print(x)
print(x.dict())
print(y)
print(z)

它们是不同的,这很好。但是,当我尝试生成时StructList,出现了一些问题:

structlist1 = Functional.StructList()
structlist1.append(x)
structlist1.append(y)

for struct in structlist1:
    print(struct)

print()

structlist2 = Functional.StructList()
    
for struct in structlist2:
    print(struct)

问题是 - 当我首先创建时StructList,它会完美生成。然后我在这里Struct通过方法添加一些对象append,我创建了上面介绍的东西。这个对象正确地保存在 thisStructList中。但是,当我创建 secondStructList并尝试检查里面的内容时,我发现这不是空的。它包含Structfirst 中的所有对象StructList,但我没有链接它,我只是创建了这个类的新实例。我认为它应该是空的,并且不与创建的链接。所以,问题是 - 如何解决这类问题?我不想使用默认list类来创建这个StructList子类,但想使用这个,创建了一个。

此外,这些对象具有不同的地址:

print(structlist1)
print(structlist2)
print(structlist1 == structlist2)

<Scripts.Generators.Functional.StructList object at 0x7f12cb650700>
<Scripts.Generators.Functional.StructList object at 0x7f12cb650280>
False

从评论更新Struct类后,没有解决这个问题:

class Struct:

    def __init__(self, **entries):
        self.__dict__.update(entries)

    def __iter__(self):
        return iter(vars(self).values())

    def __len__(self):
        return len(self.__keys__)

    def __getitem__(self, item):
        return self.__dict__.get(item)

    def add(self, **entries):
        for key, value in entries.items():
            self.__dict__[key] = value

    @staticmethod
    def from_struct(struct: 'Struct'):
        return Struct(**struct.dict())

    def dict(self):
        return dict(vars(self))

标签: pythonoop

解决方案


推荐阅读