python-3.x - Python 3.6+ 可以是字符串或任何类的参数注释
问题描述
from typing import Union, Callable, Any
def map_type(t) -> str:
if isinstance(t, str):
_type = t
else:
_type = t.__name__
return {
'float': 'float',
'int': 'integer',
'number': 'float',
'bool': 'boolean',
'date': 'date',
'datetime': 'datetime',
'list': 'list',
'str': 'string'
}.get(_type)
那么注释t该怎么写呢?
def map_type(t: Union[str, Any])->str: pass
解决方案
不是任何对象,而是任何类?类的类型是type
>>> type(int)
type
>>> type(str)
type
因此,您可能想要 str 和 type 的联合,
def map_type(t: Union[str, type]) -> str:
...
该Any
类型仅表示“未检查类型”,这在联合中是无用的。
推荐阅读
- node.js - 是否可以在 MERN Google App Engine 上部署 WordPress 博客?
- listview - Flutter 在大列表上设置 initialScrollOffset 变得滞后且非常慢
- android - 关闭应用程序时,Firebase 推送通知不会在 Android 上触发 onMessageReceive
- html - CSS 编码不适用于
- javascript - 无法从 React 前端向 Node.js 后端发送 POST 请求
- python-3.x - 使用python在小时内比较两次
- c++ - 从看似不相关的代码中改变 for 循环行为
- jquery - jQuery如何检查两个或多个选择下拉元素是否已更改
- javascript - 我想知道为什么事件侦听器不起作用?似乎它应该工作,但它不是
- ssl - 找不到 ngrok websocket 安全的证书