Python:创建文档抽象数据类型并添加字典变量

我试图在Python中创建文档抽象数据类型,并向其中添加一个字典变量,以跟踪文档中唯一单词及其出现的频率。我在正确的轨道上吗?我是抽象数据类型的新手,我不确定自己是否做对了。

class Document:
    dict = {}
评论
宇智波~
宇智波~

You need to use Abstract Base Classes for defining abstract classes in Python:

from abc import ABC

class Document(ABC):
    pass

Another problem in your code is that the way you defined your dict attribute makes it mutable across all instances of Document. For example:

>>> d1 = Document()
>>> d2 = Document()
>>> d1.dict['foo'] = 'bar'
>>> d2.dict
{'foo': 'bar'}

除非这是理想的行为(不是因为每个文档中的字数都不同),否则您需要以下内容:

from abc import ABC

class Document(ABC):
    def __init__(self, dict):
        self.dict = dict

这条路,

>>> d1 = Document({'foo': 'bar'})
>>> d2 = Document({'123': '456'})
>>> d1.dict
{'foo': 'bar'}
>>> d2.dict
{'123': '456'}
点赞
评论