reflection – Convert a python type object to a string

reflection – Convert a python type object to a string

print type(someObject).__name__

If that doesnt suit you, use this:

print some_instance.__class__.__name__

Example:

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

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

>>> class A(object): pass

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

what do you mean by convert into a string? you can define your own repr and str_ methods:

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

or i dont know..please add explainations 😉

reflection – Convert a python type object to a string

print(My type is %s % type(someObject)) # the type in python

or…

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

Leave a Reply

Your email address will not be published. Required fields are marked *