简体   繁体   English

如何将类型信息作为字符串获取?

[英]How can I get type information as a string?

I have an object 'something'.我有一个 object '东西'。 Calling it returns (for example):调用它返回(例如):

<CTE 'WITH' at 0x1853B0A2888>

What is the best way to get this output (or the CTE 'WITH' part) as a string?将这个 output (或CTE 'WITH'部分)作为字符串的最佳方法是什么? The closest I got was by using我得到的最接近的是使用

str(something.__repr__)

which returns返回

"<bound method Token.__repr__ of <CTE 'WITH' at 0x1853B0A2888>>"

which I can then trim/clean up to get what I want.然后我可以修剪/清理以获得我想要的东西。 But I'd like to hear about better ways to go about this.但我想听听关于 go 的更好方法。

(Sorry for the vague title, I don't know the right words for phrasing it better.) (对不起,模糊的标题,我不知道更好的措辞。)

If we're speaking about figuring our class name of an object as a string in Python, then I can suggest you to try this:如果我们正在谈论将 object 的 class 名称计算为 Python 中的字符串,那么我建议您尝试以下操作:

>>> a = "adsf"
>>> a.__class__.__name__
'str'

You can you the builtin function id() on your object.您可以在 object 上使用内置的 function id()

class A():
    def __init__(self):
         self.a = 5

def main():
    object = A()
    print(object)
    print(id(object))

will print <__main__.A instance at 0x02968558> in the first print() and 43418968 in the second.将在第一个print()中打印<__main__.A instance at 0x02968558> ,在第二个中打印43418968 43418968 is just 0x02968558 converted to base 10 43418968 只是 0x02968558 转换为基数 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM