将Python 'type'对象转换为字符串

226 投票
5 回答
224989 浏览
提问于 2025-04-16 11:53

我想知道怎么用Python的反射功能把一个Python的'type'对象转换成字符串。

举个例子,我想打印一个对象的类型。

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

5 个回答

6
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)
14
>>> class A(object): pass

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

你说的“转换成字符串”是什么意思呢?你可以自己定义 __repr____str__ 这两个方法:

>>> 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

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

348
print(type(some_object).__name__)

如果这个不适合你,可以试试这个:

print(some_instance.__class__.__name__)

举个例子:

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

另外,使用新式类和旧式类时,type()的表现似乎有些不同(新式类是指继承自object的类)。对于新式类,type(someObject).__name__会返回类的名字,而对于旧式类,它会返回instance

撰写回答