Python中类型的字符串表示法

2024-04-20 08:25:04 发布

您现在位置: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笔记本打印正确,如果这是在细胞的最后一行。你知道吗

为什么会发生这种错误?获取类型字符串的正确方法是什么?你知道吗


Tags: of函数字符串an类型objecttypeeval
2条回答

考虑到问题的模糊性,print(type("cow"))是一种误导。是牛吗

  • 字符串“cow”
  • 一个名为cow的变量(在本例中碰巧是字符串)

不管怎样,这里有一种方法既适用于两种情况:

>>> cow = "Moo!!"
>>>
>>> # Variable
...
>>> cow.__class__.__name__
'str'
>>> # String literal
...
>>> "cow".__class__.__name__
'str'

有关详细信息,请查看[Python 3.Docs]: Built-in Types - Special Attributes。你知道吗

也许你想要

type("cow").__name__

什么?你知道吗

相关问题 更多 >