Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a python 'type' object to a string

I'm wondering how to convert a python 'type' object into a string using python's reflective capabilities.

For example, I'd like to print the type of an object

print "My type is " + type(someObject) # (which obviously doesn't work like this) 
like image 287
Rehno Lindeque Avatar asked Feb 15 '11 19:02

Rehno Lindeque


People also ask

How do you turn an object into a string?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

Is type object a string Python?

The best way to checks if the object is a string is by using the isinstance() method in Python. This function returns True if the given object is an instance of class classified or any subclass of class info, otherwise returns False.

How do I convert an instance to a string in Python?

Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.

Which one is converting a type to string?

The global method String() can convert booleans to strings. The Boolean method toString() does the same.


2 Answers

print type(someObject).__name__ 

If that doesn't 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.

like image 123
Gabi Purcaru Avatar answered Oct 18 '22 23:10

Gabi Purcaru


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

like image 31
Ant Avatar answered Oct 19 '22 01:10

Ant