首页 > 解决方案 > 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

标签: pythonpython-3.x

解决方案


也许您可以定义一个新类型并在代码中使用它。见下文

有了这个,您可以更改 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)

推荐阅读