【问题标题】:Python types: dict of somethingPython 类型:某物的 dict
【发布时间】:2018-08-05 21:48:27
【问题描述】:

有没有办法通知 python (3.6+) 我的属性是某个东西的字典?

我想要什么:

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

【问题讨论】:

  • the documentation,例如Dict[str, Sentence]
  • 你从什么映射到什么?
  • "a dict of something" 是模棱两可的。你的意思是Sentence 作为键(用其他具体或通用的东西作为值)还是作为值?

标签: python python-3.x data-structures types type-hinting


【解决方案1】:

为了输入字典,您必须从输入中导入字典。打字模块还提供对其他打字类型的支持。如:元组、列表和联合。您可以使用这些相同的类型来指示返回值。

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

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多