在 python 中使用类型别名然后将其声明为变量是个好主意吗?

Is it a good idea to use a type alias name in python and then declare that as a variable?

我正在看这样的代码:

class DeckManager:

   decks: Dict[str, Any]

   def __init__(self, col: a) -> None:

        self.decks = {}

decks: Dict[str, Any] 指定类型别名是否正确?如果是这样,那么在代码后面使用:self.decks 是否有意义。这不令人困惑吗?

不,decks 不是 类型别名。这是一个类型注释。根据 PEP-484:

Type aliases are defined by simple variable assignments.

或者根据typing documentation

A type alias is defined by assigning the type to the alias.

因此,为变量分配任何可能是有效类型注释的内容都是类型别名:

decks = Dict[str, Any]

这样 decks 将是类型别名。

但是当你使用冒号时,你是在注释那个变量,而不是创建类型别名:

decks: Dict[str, Any]

根据 Python 的类型注释约定,您只是将 DeckManager 实例的 decks 属性注释为 Dict[str, Any].