首页 > 解决方案 > 试图在他们的类中保存实例

问题描述

我的问题是我想将一个类的实例保存在一个类字典(这里命名为目录)中。每次我创建一个新实例时,我都希望它存储在目录中,键是 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?

感谢您的回答!

标签: python-3.x

解决方案


我不是 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)

莎拉
莎拉



推荐阅读