python - Python定义具有其他变量类型的变量
问题描述
我可以从其他变量类型中定义变量的类型吗?
示例:我创建了 USER:
class User(BaseModel):
id: str # Not sure if will be str, int or UUID
tags: Optional[List[str]]
name: str
现在,在其他地方,我有一个使用 User.id 作为参数的函数:
def print_user_id(user_id: str): # If I change type of User.id, I need to update this!
pass
我怎么能说是的user_id
类型type(User.id)
?
像:
def print_user_id(user_id: type(User.id)): # But, If I change type of User.id, I DON`T NEED to update this :)
pass
解决方案
也许您可以定义一个新类型并在代码中使用它。见下文
有了这个,您可以更改 UserId 的实际类型,而不会影响其余代码。
from typing import NewType, Optional, List
UserId = NewType('UserId', int)
class BaseModel:
pass
class User(BaseModel):
id: UserId
tags: Optional[List[str]]
name: str
def print_user_id(user_id: UserId):
print(user_id)
推荐阅读
- python - selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable - when trying to .send_keys() to text boxes
- javascript - 使用 Javascript 创建复杂的表体结构
- python - Pandas 按值将行折叠成元组
- python - 从列表中添加多个文件时出现问题
- python - 如何在 Python 中定义数组类?
- flutter - 使用 Flutter path_provider 查找使用 Adobe AIR 构建的以前版本的应用程序存储的 txt 文件
- python - 如果有某种方式知道或检查某些变量是否包含字典列表?
- c++ - 如何强制 C++ 预处理器宏中的特定类型?
- javascript - 如何防止 Wordpress 显示 Google 组织结构图行线?
- json - 使用带有数据集的公共类从 vb.net 创建 json 文件