python-3.x - 试图在他们的类中保存实例
问题描述
我的问题是我想将一个类的实例保存在一个类字典(这里命名为目录)中。每次我创建一个新实例时,我都希望它存储在目录中,键是 self.id 值,值是实例本身。
我已经用new寻找了一些解决方案,但似乎new只能返回一个实例而不初始化它,因为init可以完成这项工作。
def Mother():
id_m=0
catalog={}
def __init__(self):
self.value=0
self.id=None
self.sub_dict={}
self.id_attrib()
Mother.id_m+=1
def id_attrib(self):
if self.id==None:
self.id=id_m
else:
pass
def __sub__(self,sub):
if type(sub) is not Mother:
return self
else:
index=0
while index not in self.sub_dict.keys():
index+=1
self.sub_dict[index]=sub
到目前为止,这段代码只初始化了一个新实例。我想做的进一步是提供一个类方法来更新self.sub_dict中的实例。
s1=Mother()
s2=Mother()
s1=s1-s2 ## adds s2 to the self.sub_dict
s2.value=150 ##How to update the value in self.sub_dict?
感谢您的回答!
解决方案
我不是 100% 确定你想用sub做什么,但如果这让你更接近,请告诉我。如果您需要跟进,请添加评论,我会尽我所能提供帮助;
from typing import Dict
class Mother():
all_mothers = dict() # type: Dict[str, Mother]
def __init__(self, last_name, first_name):
self.last_name = last_name # type: str
self.first_name = first_name # type: str
Mother.all_mothers[last_name] = self
jones = Mother("Jones", "Martha")
smith = Mother("Smith", "Sarah")
print(smith.first_name)
print(Mother.all_mothers['Smith'].first_name)
smith.first_name = "Jane"
print(smith.first_name)
print(Mother.all_mothers['Smith'].first_name)
Mother.all_mothers["Jones"].first_name = "Sue"
print(jones.first_name)
莎拉
莎拉
简
简
苏
推荐阅读
- python - 对于带有列表和文件夹传输的其他内容
- xmlhttprequest - 无法在最近的 chrome 更新中解析 Access-Contro-Allow-Headers
- android - 如何将 TensorFlow AI 模型(物体识别)放入 Android APP?
- node.js - 更新nodejs中嵌套对象的值
- scala - Scala:如何检查 Array[T] 的类型
- c - 我需要帮助从 c 中的用户输入中接受换行符
- ios - 如何使用 Swift 为 4D 数据创建 CoreML MLMultiArray 以在 iOS 上进行预测?
- flutter - 带有firestore的依赖颤动下拉按钮
- c - 是否可以在 SIGSEGV 处理程序中暂停 C 程序以进行进一步调查?
- sql - 如何在 SQL 数据库中构造两种类型的用户?