Python类型:dict of something

2024-04-25 01:13:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法告诉python(3.6+)我的属性是某个事物的dict?你知道吗

我想要的是:

def classify(self, sentenses: dict(Sentence)):  # <-- dict of Sentence
  for s in sentences:
    a = s.attribute

Tags: ofinselffor属性defsentencesattribute
1条回答
网友
1楼 · 发布于 2024-04-25 01:13:19

为了输入Dict,您必须从输入中导入Dict。输入模块还支持其他类型的输入。例如:元组、列表和并集。您可以使用这些相同的类型来指示返回值。你知道吗

from typing import Dict


class Sentence:

    def __init__(self):
        self.some_atr = ""
        self.another_atr = ""


def classify(sentences: Dict[str, Sentence]):  # <  dict of Sentence
  for k, v in sentences.items():
      print(v.some_atr)


s1 = Sentence()
s1.some_atr = "First"

s2 = Sentence()
s2.some_atr = "Second"

sen = {'first': s1, 'second': s2}
classify(sen)

https://docs.python.org/3/library/typing.html

相关问题 更多 >