【问题标题】:Overiding function with specific type in python 2python 2中具有特定类型的覆盖函数
【发布时间】:2019-12-19 17:30:28
【问题描述】:

当特定类型作为参数传递时,我试图覆盖一个函数。

def __getitem__(self, x: str):
    ...

这在 Python 3 中有效,但在 Python 2 中无效。在 Python 2 中是否有等价物或实现相同功能的某种方式?

【问题讨论】:

    标签: python python-2.7 function types parameters


    【解决方案1】:

    Python 2 没有类型提示。你可以不给出类型提示,而是随心所欲地处理函数体。

    def __getitem__(self, x):
        if isinstance(x, str):
            return self.data[x]
        elif isinstance(x, int):
            return self.numbers[x]
        else:
            return 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2022-11-03
      • 2013-04-01
      • 1970-01-01
      相关资源
      最近更新 更多