如何用空字典初始化 class - Python

How to initialize class with empty dictionary - Python

抱歉,如果这个问题是业余的,我是 classes/objects 的新手。我浏览了其他 Stack 帖子,但没有得到我的问题的明确答案。

我想用空字典初始化一个 class,然后将 keys/values 添加到字典中。我该怎么做?

这是我现在拥有的:

class Network(object):
    
    self.dict = {}

    def __init__(self, key, value):
        """
        Initializes key and value of dictionary
        """
        self.key = key
        self.value = value   
        
    def add_key(key):
        """
        Should add the key to the dictionary if it doesn't exist
        """
        #if the key is not in the dictionary, add the key, and a value which is an empty list
        if key not in self.dict:
            self[key] = []

Python怎么知道我初始化的keyvalue是我创建的空字典dict的元素?

编辑: 我根据 Ghost Ops 的建议更新了代码,但在尝试测试时收到属性错误。

class Network(object):
    

    def __init__(self, key, value):
        """
        Initializes key and value of dictionary
        """
        self.dicts = {}
        self.key = key
        self.value = value   
        
    def add_key(key):
        """
        Should add the key to the dictionary if it doesn't exist
        """
        #if the key is not in the dictionary, add the key, and a value which is an empty list
        if key not in self.dicts:
            self[key] = []
       
        # to test if the code returns correctly:
        def get_dicts(self):
            return self.dicts

test_dic = {13: [1, 2, 3], 14:[4, 5]}
print(test_dic.get_dicts())

错误: 'dict' object has no attribute 'get_dicts'

我可能测试的代码有误吗?/抱歉,我对此很陌生

您可以从 dict 继承您的 class,基本上您的 class 也将充当字典。您的 add key 方法仍然可以正常工作,只需将 self.dict 更改为 self.keys() 即可取回所有现有密钥。键和值变量是不必要的。

class Network(dict):

    def __init__(self, key, value):
        """ Initializes superclass """
        super().__init__()  
        
    def add_key(key):
        """ Should add the key to the dictionary if it doesn't exist """
        if key not in self.keys():
            self[key] = []