python - 生成的类在 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
并尝试检查里面的内容时,我发现这不是空的。它包含Struct
first 中的所有对象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))
解决方案
推荐阅读
- tensorflow-data-validation - 如何启用数值特征漂移?
- c# - 如何在收到请求时使用异步代码加速 Api 控制器响应以运行另一个任务?
- java - 调用 RESTful 服务时出现 FileNotFoundException
- php - PHP 与 MySQL Windows 身份验证的兼容性
- python - 提取字符或拆分列(dtype float64)
- c# - 实体框架核心 - 延迟加载不适用于 Getters
- python - 如何将json文件输出(子进程)加载到python中的变量中?
- javascript - 无法解决“TypeError:不是函数”错误
- php - 如何从选择列表中选择选项,然后根据数据库记录更改第二个选择列表?
- javascript - 我可以使用中间件代理从 localhost url 重定向或路由到另一个