![](/img/trans.png)
[英]Check type of object against a string representation of a type object in Python
[英]String representation of type in 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筆記本會正確打印。
為什么會發生此錯誤? 僅獲取Type字符串的正確方法是什么?
也許你想要
type("cow").__name__
?
考慮到問題的模棱兩可, print(type("cow"))
有點誤導。 是牛 :
無論如何,這是一種適用於兩者的方法:
>>> cow = "Moo!!" >>> >>> # Variable ... >>> cow.__class__.__name__ 'str' >>> # String literal ... >>> "cow".__class__.__name__ 'str'
有關更多詳細信息,請檢查[Python 3.Docs]:內置類型-特殊屬性 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.