@dataclass
class MarkdownIsOpen:
ChapterOpen: bool = False
SectionOpen: bool = False
ArticleOpen: bool = False
或者:
^{pr2}$
请注意,这需要Python3.7。在
如果使用Python<;=3.6,那么普通类也可以。类并不昂贵,它们向用户提供了一个提示:您的函数不需要任何旧的dict-类,而是一个具有以下属性的特殊容器。在
例如,将其与C的struct或Scala的{}进行比较,它们的作用基本相同。在
此外,您甚至可以重写__slots__和/或__getitem__以允许类似dict的访问,并阻止添加新属性:class MarkdownIsOpen:
__slots__ = ('ChapterOpen', 'SectionOpen', 'ArticleOpen')
def __init__(self):
self.ChapterOpen = False
self.SectionOpen = False
self.ArticleOpen = False
def __getattr__(self, key):
return getattr(self, key)
def __setattr__(self, key, value):
setattr(self, key, value)
示例:m = MarkdownIsOpen()
m['ChapterOpen'] = True
print(m['SectionOpen'])
m['Nonexistent'] = False
输出:False
AttributeError: 'MarkdownIsOpen' object has no attribute 'Nonexistent'