[英]Is it a good idea to use a type alias name in python and then declare that as a variable?
I am looking at code like this:我正在看这样的代码:
class DeckManager:
decks: Dict[str, Any]
def __init__(self, col: a) -> None:
self.decks = {}
Is it correct that decks: Dict[str, Any] is specifying a Type Alias?甲板:Dict[str, Any] 指定类型别名是否正确? If so then does it make sense to use: self.decks later in the code.
如果是这样,那么在代码后面使用:self.decks 是否有意义。 Is that not confusing?
这不令人困惑吗?
No, decks
is not a type alias.不,
decks
不是类型别名。 It is a type-annotation.它是一种类型注释。 According to PEP-484 :
根据PEP-484 :
Type aliases are defined by simple variable assignments.
类型别名由简单的变量赋值定义。
Or according to the typing
documentation :或根据
typing
文档:
A type alias is defined by assigning the type to the alias.
通过将类型分配给别名来定义类型别名。
So assigning to a variable anything that would be a valid type annotation is a type alias.因此,将任何可能是有效类型注释的内容分配给变量都是类型别名。 So:
所以:
decks = Dict[str, Any]
When you use the colon, you are annotating that variable, not creating an alias:当您使用冒号时,您是在注释该变量,而不是创建别名:
decks: Dict[str, Any]
Would be a type alias.将是类型别名。 According to Python's type annotation conventions, you've simply annotated the
decks
attribute for DeckManager
instances to have type Dict[str, Any]
.根据 Python 的类型注释约定,您只需将
DeckManager
实例的decks
属性注释为具有类型Dict[str, Any]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.