【发布时间】:2019-10-15 01:33:27
【问题描述】:
给定以下代码:
from typing import Tuple
class Grandparent:
items: Tuple[str, ...] = ()
class Parent(Grandparent):
items = ('foo',)
class Child(Parent):
items = ('foo', 'bar')
mypy 报如下错误:
error: Incompatible types in assignment (expression has type "Tuple[str, str]", base class "Parent" defined the type as "Tuple[str]")
像这样更改代码(在Parent 类中再次指定相同的类型)满足mypy:
from typing import Tuple
class Grandparent:
items: Tuple[str, ...] = ()
class Parent(Grandparent):
items: Tuple[str, ...] = ('foo',)
class Child(Parent):
items = ('foo', 'bar')
既然items 在所有位置的分配都满足相同/原始定义,为什么我需要在类层次结构中的多个位置为items 重新指定相同的类型?有没有办法避免需要这样做?
【问题讨论】:
标签: python mypy python-typing