代码之家  ›  专栏  ›  技术社区  ›  Davi Daniel Siepmann

Python类型:dict of something

  •  0
  • Davi Daniel Siepmann  · 技术社区  · 7 年前

    有没有办法告诉python(3.6+)我的属性是某个内容的dict?

    我想要的是:

    def classify(self, sentenses: dict(Sentence)):  # <-- dict of Sentence
      for s in sentences:
        a = s.attribute
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Dave    7 年前

    要以Dict形式键入,必须从键入中导入Dict。键入模块还支持其他类型的键入。例如:Tuple、List和Union。您可以使用这些相同的类型来指示返回值。

    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