【问题标题】:Convert a python 'type' object to a string将 python 'type' 对象转换为字符串
【发布时间】:2011-02-15 19:58:04
【问题描述】:

我想知道如何使用 python 的反射功能将 python 'type' 对象转换为字符串。

例如,我想打印一个对象的类型

print "My type is " + type(someObject) # (which obviously doesn't work like this)

【问题讨论】:

  • 您认为对象的“类型”是什么?您发布的内容有什么不妥之处?
  • 抱歉,print type(someObject) 确实有效 :)

标签: python reflection


【解决方案1】:
print type(someObject).__name__

如果这不适合您,请使用:

print some_instance.__class__.__name__

例子:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

此外,在使用新式类与旧式类(即从object 继承)时,type() 似乎存在差异。对于新式类,type(someObject).__name__ 返回名称,对于旧式类,它返回 instance

【讨论】:

  • 执行print(type(someObject)) 将打印全名(即包括包)
【解决方案2】:
>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 

转换成字符串是什么意思?您可以定义自己的 reprstr_ 方法:

>>> class A(object):
    def __repr__(self):
        return 'hei, i am A or B or whatever'

>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever

或者我不知道..请添加解释;)

【讨论】:

  • 顺便说一句。我认为您的原始答案有 str(type(someObject)) 这也很有帮助
【解决方案3】:
print("My type is %s" % type(someObject)) # the type in python

或者...

print("My type is %s" % type(someObject).__name__) # the object's type (the class you defined)

【讨论】:

    【解决方案4】:

    如果您想使用 str() 和自定义 str 方法。这也适用于 repr。

    class TypeProxy:
        def __init__(self, _type):
            self._type = _type
    
        def __call__(self, *args, **kwargs):
            return self._type(*args, **kwargs)
    
        def __str__(self):
            return self._type.__name__
    
        def __repr__(self):
            return "TypeProxy(%s)" % (repr(self._type),)
    
    >>> str(TypeProxy(str))
    'str'
    >>> str(TypeProxy(type("")))
    'str'
    

    【讨论】:

      【解决方案5】:

      通过使用 str() 函数,您可以做到这一点。

       typeOfOneAsString=str(type(1))  # changes the type to a string type
      

      【讨论】:

        猜你喜欢
        • 2021-08-03
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-16
        • 1970-01-01
        相关资源
        最近更新 更多