首页 > 解决方案 > Python中类型的字符串表示

问题描述

我希望在 eval 语句中使用类型函数,所以我只需要该函数的字符串表示。例如:

print(type("cow"))
<class 'str'>

在这里我需要它输出'str'。但是当我尝试时:

type("cow").__str__()
TypeError: descriptor '__str__' of 'str' object needs an argument
type("cow").__repr__()
TypeError: descriptor '__repr__' of 'str' object needs an argument

奇怪的是,如果这是单元格中的最后一行,Jupyter notebook 会正确打印它。

为什么会发生此错误?仅获取 Type 字符串的正确方法是什么?

标签: python

解决方案


也许你想要

type("cow").__name__

?


推荐阅读